what really happens with extend and inheritance?
I constructed three class: Age, Father and Son (extending father) and
I wonder what will happen (see code down)?
Sure the Son's class should call the constructor of the Father's (default constructor), right!
But why get's also the Father's age initialized?
Here is the output:
56 is father's age
13 is son's age
BUILD SUCCESSFUL (total time: 0 seconds)
Code:
package willemlearningjava;
class Age {
int a=0;
Age(int a) {
// System.out.println(" inside constructor Age");
this.a = a;
System.out.print("" + a);
}
}
package willemlearningjava;
class Father {
Age age = new Age(56);
Father() {
System.out.print(" is father's age ");
System.out.println();
}
}
package willemlearningjava;
public class Son extends Father {
Age age = new Age(13);
Son() {
System.out.print(" is son's age ");
System.out.println();
}
public static void main(String[] arc) {
Son s = new Son();
}
}
Re: what really happens with extend and inheritance?
INHERITANCE
INHERITANCE
Hope the links clear the concept.
Re: what really happens with extend and inheritance?
Son extending father is a bad design, and a misuse of inheritance. Is a son a specialized type of father? No, I thought not.
db
Re: what really happens with extend and inheritance?
Slight abuse of inheritance aside, trace the code.
Both Father and Son have an 'age' attribute.
This attribute is initialised in their respective constructors.
So follow the code through by hand and see what gets called.