35
Constructors in Java
Constructors are used every time to initialize instance variables. There are some additional rules associated with constructors that are often asked in interviews.Hence revising those here through a blog post.
class A{
A(){ //default no arg constructor
}}
class A{
A(){
//some code
}
A(int x){
//some code
}
A(float x){
//some code
}
A(float x,int y){
//some code
}
A(int x,float y){
}
A(int z){}//THIS WILL GIVE COMPILE ERROR SInce its already defined on top.
}
A a=new A();
new A();//goes to first matching constructor
class A{
A(){
System.out.println("A"); //I
A(int x){
this(); //this will go to constructor A();
System.out.println("AA"); //II
}
}
class App{
public static void main(String[]args){
new A(5);
}}
OUTPUT:
A
AA
class A{
A(){
System.out.println("A"); //I
}
}
class B extends A{
B(){
super(); //this is called implicitly refer next point also
System.out.println("B");
}}
class HelloWorld {
public static void main(String[] args) {
new B();
}
}
OUTPUT:
A
B
Note:If a class does not extend any class it by default extends the Object class.
Do Try this code in your ide to see it for yourself
Do Try this code in your ide to see it for yourself
class A{
A(){
//super will be called implicitly at the first line of this constructor and here since it does not extend any class it will extend the Object class
System.out.println("A"); //I
}
A(int x){
//super will be called implicitly at the first line of this constructor
System.out.println("AA");
}}
class HelloWorld {
public static void main(String[] args) {
new A(5);
}
}
OUTPUT:
A
AA
That's all for constructors in Java. If any mistake content or otherwise feel free to let me know in the comment section.
Happy Learning :)
35