• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Constructors  RSS feed

 
Sidharth Pallai
Ranch Hand
Posts: 137
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the code doesn't get compiled? Can anyone explain me.
 
Madhu Sagar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are creating a sub class by using superclass.
Inheritance rule is that

The superclass should have a default constructor then only we can create a sub class for it.

So now compile this.
class Y{
Y(){}
Y(String s){}

}
class Z extends Y{
Z(){}
}
 
Sidharth Pallai
Ranch Hand
Posts: 137
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Madhu,
Why should i need to declare a default constructor in the super, if there exist a implicit default constructor declaration in the super.
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why should i need to declare a default constructor in the super, if there exist a implicit default constructor declaration in the super.


No when you declare your own constructor in any class , the compiler no longer provide its own default constructor !!

If thats clear,

Now see this code :



when you call the constructor of sub-class , the compiler execute the firs line as the call to super class constructor ..

in your original code , you are not providing the default constructor like this :


and when compiler sees this code :


it replace first line of the subclass constructor like this :


so there is no default constructor for super class , hence compiler raise an error !!

Hope this help !
 
Sidharth Pallai
Ranch Hand
Posts: 137
Hibernate Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Sagar. I understood the stuff hence corrected myself.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sagar Rohankar:
No when you declare your own constructor in any class , the compiler no longer provide its own default constructor !!

Ding ding ding! We have a winner!

The compiler only inserts a default constructor if you don't provide any constructors at all. And all that constructor does is call its parent's class' constructor without parameters, like so:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!