Java Constructor

 Constructor

         Constructor is a special member function of a class which is automatically called whenever a new object is created.

Rules

  1. It must have the same name as the class name
  2. It cannot have any return type not even void
  3. It must be declared under the public section

Types of Constructor

  • Default Constructor 
  • Parameterized Constructor 
  • Copy Constructor

Example 01:Default Constructor

package Constructor;

class square //class definition

{

int side,area;


square()

{

side=20;

}

void calculate()

{

area=side*side;

}

void display()

{

System.out.println("Area of square="+area);

}

}


class constructor

{

public static void main(String args[])

{

square s=new square(); //creating object and constructor is called

s.calculate();

s.display();

}

}



Example 02: Parameterized Constructor

package Constructor;

class Square_prgm //class definition

{

int side,area;


Square_prgm(int side)

{

this.side=side;

}

void calculate()

{

area=side*side;

}

void display()

{

System.out.println("Area of square=" +area);

}

}


class parameterized_constructor

{

public static void main(String args[])

{

Square_prgm s=new Square_prgm(20); //creating object and parameterized constructor is called

s.calculate();

s.display();

}

}


Example 03: Copy Constructor

package Constructor;


import java.util.Scanner;


class CopyConstructor

{

int age;

String name;


CopyConstructor(int a,String n)//parameter

{

age=a;

name=n;

}

CopyConstructor(CopyConstructor cc) //copy

{

age=cc.age;

name=cc.name;

}

void display()

{

System.out.println("Your name is : "+name + "\nAge is : "+age);

}

public static void main(String[] arg)

{

System.out.print("Enter your name and age :");

Scanner scan = new Scanner(System.in);

String name =scan.nextLine();

int age =scan.nextInt();

CopyConstructor cc = new CopyConstructor(age,name);

CopyConstructor c2=new CopyConstructor(cc);

cc.display();

c2.display();

}

/*Constructors are special methods named after the class and without a return type, and are used to construct objects.

* Constructors, like methods, can take input parameters. Constructors are used to initialize objects.

* A copy constructor is a constructor that creates a new object using an existing object of the same

* class and initialize each instance variable of a newly created object with corresponding instance

* variables of the existing object passed as argument.


Syntax :

public class_Name(const className old_object)


Example :

Public student(student o)*/

}







Post a Comment

0 Comments