Você está na página 1de 5

Constructor in Java

Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is
why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are 3 types of constructors:
Constructor

Default
Constructor

No-Argument
constructor

Parameterized
Constructor

1. Default Constructor:
If you do not define any constructor in your class, java generates one that takes no parameters for you by default. This
constructor is known as default constructor. You would not find it in your source code but it would present there.

2. Java No-arguments Constructor


A constructor that has no parameter is known as No Argument Constructor.
Syntax of default constructor:
<class_name>(){}
Example of No-arguments Constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Constructor in Java 1

Important point
Whatever constructor you write in your class cannot be called default since you are writing it. The constructor is called
default only when it has been generated by java.
Example of default constructor that displays the default values
class Student3
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null
Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here
0 and null values are provided by default constructor.

3. Java parameterized constructor


A constructor that has parameters is known as parameterized constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of
parameters in the constructor.
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}

Constructor in Java 2

Output:
111 Karan
222 Aryan

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.
Constructor

Method

Constructor is used to initialize the state of an object.

Method is used to expose behaviour of an object.

Constructor must not have return type.

Method must have return type.

Constructor is invoked implicitly.

Method is invoked explicitly.

The java compiler provides a default constructor if you


don't have any constructor.

Method is not provided by compiler in any case.

Constructor name must be same as the class name

Method name may or may not be same as class name

Constructor Overloading in Java


Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in
parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the
list and their type.
Example of Constructor Overloading
class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25

Constructor in Java 3

Important Point to Note:


If you are defining parametrised constructor then you may ran into trouble. Handle them with care :)

What kind of trouble?


Lets have a look at the code below:
class Example3
{
private int var;
public Example3(int num)
{
var=num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example3 myobj = new Example3();
System.out.println("value of var is: "+myobj.getValue());
}
}
Output: It will throw a compilation error!!.
The reason is when you dont define any constructor in your class, compiler defines default one for you,
Since here a constructor (a parameterized constructor) have been defined in above code, compiler didnt create default
one anymore .But While creating object we are invoking default one, which doesnt exist in above code. The code gives an
compilation error.
So Solution Is
Either we have to define a default constructure or we have to call the parameterized constructure

Understood till now Here are few more points about constructors
1.
2.
3.
4.

Every class has a constructor whether its normal one or a abstract class.
As stated above, constructor are not methods and they dont have any return type.
Constructor name and class name should be the same.
Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in
java but there scope is within the class only.
Like constructors method can also have name same as class name, but still they have return type, though
which we can identify them that they are methods not constructors.
If you dont define any constructor within the class, compiler will do it for you and it will create a constructor for you.
this() and super() should be the first statement in the constructor code. If you dont mention them, compiler
does it for you accordingly.
Constructor overloading is possible but overriding is not possible. This means we can have overloaded constructor in
our class but we cant override a constructor.
Constructors cannot be inherited. A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members of class. It is a member of object, so they are not inherited
by subclasses, but the constructor of the superclass can be invoked from the
If Super class doesnt have a no-arg(default) constructor then compiler would not define a default one in child class
as it does in normal scenario.
Interfaces do not have constructors.
Abstract can have constructors and these will get invoked when a class, which implements interface, gets
instantiated. (i.e. object creation of concrete class).
A constructor can also invoke another constructor of the same class By using this(). If you wanna invoke a argconstructor then give something like: this(parameter list).

5.
6.
7.
8.
9.
10.
11.
12.
13.

Constructor Chaining
14.

Constructor chaining is nothing but a scenario where in one constructor calls the constructor of its super class
implicitly or explicitly.
Suppose there is a class which inherits another class, in this case if you create the object of child class then first super
class(or parent class) constructor will be invoked and then child class constructor will be invoked.

Constructor in Java 4

class Human
{
String s1, s2;
public Human()
{
s1 ="Super class";
s2 ="Parent class";
}
public Human(String str)
{
s1= str;
s2= str;
}
}
class Boy extends Human
{
public Boy()
{
s2 ="Child class";
}
public void disp()
{
System.out.println("String 1 is: "+s1);
System.out.println("String 2 is: "+s2);
}
public static void main(String args[])
{
Boy obj = new Boy();
obj.disp();
}
}
Output:
String 1 is: Super class
String 2 is: Child class
Explanation of the example:
Human is a super class of Boy class. In above program I have created an object of Boy class, As per the rule super class
constructor (Human ()) invoked first which set the s1 & s2 value, later child class constructor (Boy()) gets invoked, which
overridden s2 value.
Note: Whenever child class constructor gets invoked it implicitly invokes the constructor of parent class.
Why java doesnt support static constructor?
Its actually pretty simple to understand Everything that is marked static belongs to the class only, for example static
method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static
keyword.
Lets back to constructors, Since each constructor is being called by its subclass during creation of the object of its subclass,
so if you mark constructor as static the subclass will not be able to access the constructor of its parent class because it is
marked static and thus belong to the class only. This will violate the whole purpose of inheritance concept and that is
reason why a constructor cannot be static.

Constructor in Java 5

Você também pode gostar