Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructors

 
mrudul joshi
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i just solved a game and i came across a question-
are the constructors inherited from a superclass to subclass?
i answered yes and the correct answer was no.
i understand that when we want to use influence the initialization of instance variables of a superclass we can use super() construct.and in fact, every time we call a onstructor of subclass, the constructor call to superclass constructor is implicitely made, if we dont write it explicitely/
is this what inheritance means?
can constructors he inherited from superclass to subclass?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If constructors were inherited, we could write
Bar b = new Bar("Hello");
but we can't. The class Bar does not inherit Foo's constructor that takes a String as an argument.
You can call this constructor from a constructor in class Bar, like this:

but that's not the same as inheriting it.
 
David Crossett
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, I just read in Core Java by Sun Publisher that although constructors are not inherited, a call to the superclasses constructor ('super') is implicitly made if you don't specify the call yourself. This implicit call is carried all the way up the chain to the Object class. They were making the point that you don't have to 'daisy-chain' finalize() calls to destroy an Object, even though it WAS daisy chained (implicitly) to be created. Just some extra info you probably didn't need!
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What David pointed out explains why the following code won't compile:

The error message you get may seem a bit cryptic, but it means that the constructor in "Level03" is illegal since Java will try and insert an implicit call to "super()". But "Level02" doesn't supply a default constructor, and Java won't add one because there is another constructor already defined.
So the [implicit] call to "super()" in the "Level03" constructor fails, and this code won't compile. This may be too advanced for a "Beginning Java" thread, but understanding constructors is a key aspect of learning Java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic