• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Prints 1 why not 2

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can someone explain it is not going into my head

public class Poly {
public static void main(String args[]) {
PolyA ref1 = new PolyC();
PolyB ref2 = (PolyB)ref1;
System.out.println(ref2.g());
}
}
class PolyA {
private int f() { return 0; }
public int g() { return 3; }
}
class PolyB extends PolyA {
private int f() { return 1; }
public int g() { return f(); }
}
class PolyC extends PolyB {
public int f() { return 2; }
}
Thanks
 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Muhammed,
If you want it to print 2 then make the method f() public/protected/default in class PolyB. In this case the method f() in class PolyB will be overridden in class PolyC.
Brian
[ March 07, 2002: Message edited by: Brian Lugo ]
 
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The runtime object in ref2 is a PolyC object. But that class has no g() method, so the g() method invoked will be the version inherited from PolyB().
PolyB simply returns the value from the method f(). However, at the scope where g() is defined, f() is a private method. Private methods are not inherited by subclasses. In fact, private methods are implicitly final. Because of this, there is no polymorphic call made. The f() method in PolyB gets executed, which returns a 1.
The methods f() in PolyB and PolyC are totally unrelated - they are not overridden, nor are they hidden. The f() method from PolyB does not exist in PolyC, and the f() method in PolyC is an implementation detail of the class that just happens to share the same name as a method in the superclass - but this is mere coincidence.
 
Muhammad Saghir
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Brian and Rob
 
Liar, liar, pants on fire! refreshing plug:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic