• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Devaka Cooray
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
Bartenders:

Inheritance Question

 
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Blood pressure normal? What do I change to get "magnificent"? Maybe this tiny ad?
Paul Wheaton's 16th Kickstarter: Gardening playing cards for gardeners and homesteaders
https://coderanch.com/t/889615/Paul-Wheaton-Kickstarter-Gardening-playing
reply
    Bookmark Topic Watch Topic
  • New Topic