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

Polymorphism Problem

 
Shilpa Bhargava
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This is a code from Bruce Eckel's Thinking in Java
public class PrivateOverride {
private void f() {
System.out.println("private f()");
}
public static void main(String args[]) {
PrivateOverride po = new Derived();
po.f();
}
}
class Derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
}
2 question on this...
1.Can u create an object of child class in the parent class itself
2.Why is the o/p "private f()" even though po is an object of type Derived.
Please help !!
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) yes
2) because private methods are inlined at compile time and therefore do not participate in polymorphism
 
Shilpa Bhargava
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Thomas ! I got it !
 
Jayadev Pulaparty
Ranch Hand
Posts: 662
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we look at it other way saying that "private methods of base class are not available (not seen) in the derived class in order to be overridden??
Please clarify
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A private method can't be overriden nohow.

8.4.6.1 Overriding (by Instance Methods)
An instance method m1 declared in a class C overrides another method with the same signature, m2, declared in class A if both
1. C is a subclass of A.
2. Either m2 is non-private and accessible from C, or m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic