File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes constructors Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructors" Watch "constructors" New topic
Author

constructors

mrudul joshi
Ranch Hand

Joined: Nov 12, 2003
Posts: 54
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

Joined: Jul 08, 2003
Posts: 24183
    
  34


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.


[Jess in Action][AskingGoodQuestions]
David Crossett
Ranch Hand

Joined: Feb 05, 2003
Posts: 102
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!


David Crossett
-nothing important to say, but learnin' plenty-
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: constructors