• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Base class constructor

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,
What will happen if I have a derived class default constructor which does not call the base class constructor as below?
Will this cause any issues?
Thanks,

public class Base{
private String st = null;
public Base (){}
public Base(String str){
st = str;
}}

public class Derived extends Base{
public Derived(){}

}
}
 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No. The first line in a constructor must either be a call to super() which calls the superclass' constructor, or a call to this() which calls an overloaded constructor. If there are no call to this() or super(), the compiler will insert an implicit call to super() as the first line of your constructor. In your case, if you create an instance of the derived class, the default constructor of your base class will be called.
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another thing: In this case, if your base class did not have a no-args constructor, you will recieve a compiler error as the implicit call to super() with no arguments would be invalid.
 
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
cross posted
 
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic