Constructor
•
Constructor is a special member function of a class which is
automatically called whenever a new object is created.
Rules
- It
must have the same name as the class name
- It
cannot have any return type not even void
- It
must be declared under the public section
Types
of Constructor
- Default Constructor
- Parameterized Constructor
- Copy 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();
}
}
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();
}
}
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)*/
}
0 Comments