Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Prints 1 why not 2

 
Muhammad Saghir
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • 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
 
Brian Lugo
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • 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 ]
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks Brian and Rob
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic