Constructors
Constructors
}
public myclass(String name)
{
// This constructor has one parameter, name.
}
}
Types of constructors
1. no-argument constructor:
A constructor that has no parameter is known as default constructor.
If the constructor is not defined in a class, then compiler creates default constructor
(with no arguments) for the class.
If we write a constructor with arguments or no-argument then compiler does not
create default constructor.
Default constructor provides the default values to the object like 0, null etc. depending
on the type.
Example1:Constructor
class Rectangle
{
int length;
int width;
Rectangle(int x,int y) //constructor method
{
length=x;
width=y;
}
int rectArea()
{
return(length*width);
}
}
class RectangleArea
{
public static void main (String args[])
{
Rectangle rect1=new Rectangle(15,10); //calling constructor
int area1=rect1.rectArea();
System.out.println(“Area =”+area1);
}
}
constructor overloading
Like methods, we can overload constructors for creating objects in different ways.
Compiler differentiates constructors on the basis of numbers of parameters, types of
the parameters and order of the parameters.
// Java Program to illustrate constructor overloading
import java.io.*;
class myclass
{
// constructor with one argument
myclass (String name)
{
System.out.println(“Constructor with one “ + “argument - String : “ + name);
}
// constructor with two arguments
myclass (String name, int id)
{
System.out.print(“Constructor with two arguments : “ +” String and Integer : “ + name
+ “ “+ id);
}
// Constructor with one argument but with different type than previous.
myclass (long num)
{
System.out.println(“Constructor with one argument : “ +”Long : “ + num);
}
}
class myclassmain
{
public static void main(String[] args)
{
myclass m1 = new myclass (“JAVA”);
myclass m2 = new myclass (“Python”, 2017);
myclass m3 = new myclass(3261567);
}
}
Constructors are different from methods in Java
• Constructor(s) must have the same name as the class within which it defined while it
• void if does not return any value.
• Constructor is called only once at the time of Object creation while method(s) can be
called any numbers of time.
creating an Object
The class provides the blueprints for objects. The objects are the instances of the class. In
Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The ‘new’ keyword is used to create the object.
• Initialization − The ‘new’ keyword is followed by a call to a constructor. This call
initializes the new object