Wednesday, 11 September 2013

Understanding Inheritance and keyword "extends"

Understanding Inheritance and keyword "extends"

I'm a beginner and currently reading inheritance and polymorphism. I'm
having some confusion in terms of the keyword "extend" and how
constructors are called. Here's the code:
public class Test {
public static void main(String[] args) {
new B();
}
}
class A {
int i = 7;
public A() {
System.out.println("i from A is " + i);
}
public void setI(int i) {
this.i = 2 * i;
}
}
class B extends A {
public B() {
setI(20);
System.out.println("i from B is " + i);
}
public void setI(int i) {
this.i = 3 * i;
}
}
I know that by calling B() in line 3, class A's constructor is invoked,
and then B's is invoked (is that right?) and thus it displays "i from A is
7" and then "i from B is 60". But can someone explain the importance of
this? Why is int i in B completely different from in i in A? Again, I'm
having trouble following the "path" of the code after the line new B(). If
someone could explain each step after B() is invoked, that would be much
appreciated.

No comments:

Post a Comment