Java Constructors
Java Constructors
BY-
KUSHAGRA KRISHNA
CONTENT
CONSTRUCTOR
TYPES OF CONSTRUCTOR
CREATING A CONSTRUCTOR
CONSTRUCTOR OVERLOADING
MULTIPLE CONSTRUCTORS
• A class can have more than one constructor as long as they have
different signature.
JAVA DEFAULT CONSTRUCTOR
A constructor
is called "Default
Constructor" when it doesn't have any
parameter.
EXAMPLE OF DEFAULT CONSTRUCTOR
class Bike1{
//creating a default constructor
Bike1()
{System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
CREATING A CONSTRUCTOR:
EXAMPLE
// Create a Main class
public class Main {
int x; // Create a class attribute
9
Parameterized constructor EXAMPLE
public Main(int y) {
x = y;
}
11
CONSTRUCTOR OVERLOADING EXAMPLE
MULTIPLE CONSTRUCTORS
13
MULTIPLE CONSTRUCTORS
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius)
{ x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
14
JAVA COPY CONSTRUCTOR
There is no copy constructor in java. But, we can copy the
values of one object to another like copy constructor in
C++.
There are many ways to copy the values of one object
into another in java. They are:
By constructor
15
DIFFERENCE BETWEEN CONSTRUCTOR AND
METHOD IN JAVA
16
THANK YOU