Hi,
I have a question about the Java code below. The only difference
between the PrivateParent and the PublicParent class is that void bar() is
private in PrivateParent and public in PublicParent.
The output of the program is:
$ java Main
PrivateParent.foo()
PrivateParent.bar()
PublicParent.foo()
PublicChild.bar()
In other words, polymorphism works for the PublicParent and PublicChild
classes, but not for PrivateParent and PrivateChild. Why is this?
Is the bar() method not overridden when it is private in the parent class?
Or is there something different that I do not know about?
TIA,
Samuel Topwash,
Titaantjes b.v.
---- begin Java code -----
class PrivateParent{
public void foo(){
System.out.println( "PrivateParent.foo()" ); bar();
}
private void bar(){
System.out.println( "PrivateParent.bar()" );
}
}
class PublicParent{
public void foo(){
System.out.println( "PublicParent.foo()" );
bar();
}
public void bar(){
System.out.println( "PublicParent.bar()" );
}
}
class PrivateChild extends PrivateParent{
public void bar(){
System.out.println( "PrivateChild.bar()" );
}
}
class PublicChild extends PublicParent{
public void bar(){
System.out.println( "PublicChild.bar()" );
}
}
public class Main{
public static void main( String[] args ){
PrivateChild pc = new PrivateChild();
pc.foo();
PublicChild pc2 = new PublicChild();
pc2.foo();
}
}
---- end Java code -----
Alan Krueger - 19 Mar 2006 17:48 GMT
> I have a question about the Java code below. The only difference
> between the PrivateParent and the PublicParent class is that void bar() is
> private in PrivateParent and public in PublicParent.
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.2
"Members of a class that are declared private are not inherited by
subclasses of that class."