+ 1
Can anybody explain, why the class B constructor calls the class A constructor in this code below? Thanks.
public class Program { public static void main(String[] args) { class A{ public A(){ System.out.println("a"); } } class B extends A{ public B(){ System.out.println("b"); } } B obj = new B(); } } Why the result ab, and not only b?
3 Respostas
+ 2
When you instantiate a class object it must first create all its parent classes. You can think of the parent/super classes as being a wrapper to the class you are instantiating. The constructors of each parent class must be created first since the child class is a version of that parent class and must have all the parent class's properties and methods instantiated so that they are available if needed in the creation of the child class.
Say, for instance, that the parent class A had an int variable named id that the child class B set its value in its constructor. If the parent class A hasn't been instantiated yet, then the child class would not be able to set that variable when the child class was instantiated and an error would occur or your program would crash.
In fact there is another constructor that is being called prior to the constructor of class A. All classes inherit from the base class Object.
Likewise the destructors (finalize()) of a class are called in the opposite order. This is why I said you can think of parent classes as a sort of wrapper.
The order of constructors and destructors (finalize()) would be:
Object constructor called Object()
Class A constructor called A()
Class B constructor called B()
// use class B until no longer needed
Class B destructor called finalize()
Class A destructor called finalize()
Object destructor called finalize()
This is why the output is the way it is.
+ 1
I know so, that the constructors cannot be inherited. In this case seems the opposit :)
So when i don't want to print a in this case, i must the class A constructor set as private?
+ 1
When the constructor of a class is called, it first (implicitly) calls the no arg constructor of the super class. If you want to extend a class that doesn't have a no arg constructor, you need to explicitly call super() with the relevant arguments.
http://www.geeksforgeeks.org/g-fact-67/