• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance Question

 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code has me confused:

public class T extends A {
private int k = 200;

public static void main (String[] args){
T t = new T();
System.out.println(t.doIt()); // 100 is output
System.out.println(t.k); // 200 is output

}
}

class A {
private int k = 100;
public int doIt() { return k; }
}

The output of doIt is 100. Class T inherits method doIt()from class A.
I would expect the output to be 200 of the doIt() call.
The value of k in the T class is 200 as the second println() shows.

Can somebody explain to me what I am missing ?
 
Anton Uwe
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Class T inherits method doIt()from class A." Now, what does that mean (and what does it NOT mean)?

It means: You can call doIt() on an object of type T (although doIt() is defined in A, not in T), because a T is an A, too.

It does NOT mean: JVM, please act as if the method code would be in class T.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic