• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Inheritance

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why the output is
A()
B()
A()
B(int)
A()
B(int,int)

I expected
A()
B()
A(int)
B(int)
A(int,int)
B(int,int)
 
Ranch Hand
Posts: 53
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In class B, there are three constructor. Those constructor doesn't call explicitly any constructor of its super class. In that case default constructor of super class i.e "A()" would be called. So, in all three cases default constructor of super class i.e A() is getting called.
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can get the desired output by this code:


Calling the constructor of base class explicitly, otherwise default constructor is called.

public class A {
int a;
A(){
System.out.println("A()");
}
A(int i){
System.out.println("A(int)");
}
A(int i,int j){
System.out.println("A(int,int)");
}

}

public class B extends A{
int b;
B(){
super();
System.out.println("B()");
}
B(int i){
super(i);
System.out.println("B(int)");
}
B(int i,int j){
super(i,j);
System.out.println("B(int,int)");
}
}

public class Demo {
public static void main(String args[]){
B b1=new B();
B b2=new B(100);
B b3=new B(100,200);
}

}
 
She still doesn't approve of my superhero lifestyle. Or this shameless plug:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic