Hallo,
I have a question about inheritance in Java.
I have two classes A and B, and class B, inherits from A:
public class A {
public A() {
System.out.println("Hi!");
}
}
public class B extends A {
public B() {
System.out.println("Bye!");
}
public static void main(String[] args) {
B b = new B();
}
}
When I run program B, the output is:
Hi! Bye!
My question is: why the constructor of class A is invoked, when I create and object of class B ? I know that B inherits everything from A - all instance or class variables, and all methods, and in this sense an object of B has all characteristics of A plus some other characteristics defined in B. However, I didn't know and didn't imagine that when I create an object of type B, the constructor of A is also invoked. So, writing this:
B b = new B();
creates two objects - one of type B, and one of type A.
This is very interesting, but can somebody explain why exactly this happens?
Thank you very much in advance.