Class7 (Constructor in Java)
Class7 (Constructor in Java)
Key Points:-
1. Definition of constructor?
2. Types of Constructor
3. Constructor overloading
4. Difference between constructor and Method
For example:
Types of Constructor
There are two types of constructors:
• Default Constructor
• Parameterized constructor
• Copy constructor
Default Constructor
In Java, a constructor is said to be default constructor if it does not have
any parameter. There can be two types of constructor i.e System Define
default constructor or user defines default constructor. If a class does
not contain any constructor then during compilation the system
generates a default constructor which is known as system define default
constructor. If a class contain a constructor with no parameter then it is
known as default constructor
Parameterised constructor
class MyClass {
int x;
MyClass(int i ) {
x = i;
Copy constructor:
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and bredth of rectang of rectangle
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
System.out.println("Copy Constructor Invoked");
length = obj.length;
breadth= obj.breadth;
}
//method to calcuate area of rectangle
int area()
{
return (length * breadth);
}
}
//class to create Rectangle object and calculate area
class CopyConstructor
{
public static void main(String[] args)
{
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect= new Rectangle(firstRect);
System.out.println("Area of First Rectangle : "+
firstRect.area());
System .out.println("Area of First Second Rectangle : "+
secondRect.area());
}
}
Output:-
Copy constructor Invoked
Area of First Rectangle :30
Area of First Second Rectangle :30
Example-2
class pnb
{
public pnb()
{}
public pnb(int x)
sa=x;
public pnb(pnb x)
this.sa=x.sa;
class CopyDemo1
obj.display();
System.out.println("object 1");
obj1.display();
System.out.println("object 2");
obj2.display();
obj2=obj;
obj2.display();
Constructor overloading:-
Example:-
// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
Constructor Method
If a constructor is not
present, a default In case of a method, no default
constructor is provided by method is provided.
Java