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

why the overriding not working???

 
Michael Lin
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Base{
//try public , then ok
private void amethod(int iBase){
System.out.println("Base.amethod");
}
}
class Abs extends Base{

public static void main(String argv[]){
Abs o = new Abs();
int iBase=0;
o.amethod(iBase);
Base b= new Abs();
b.amethod(iBase);
}

public void amethod(int iOver){
System.out.println("Over.amethod");
}
}//
//this code will cause complie error at b.amethod(iBase);
//question is: b is actually an Abs obj with an overriden method, why the error?
//and if you change the Base's method to public, it works fine
can somebody explain to me why?
thanks!
 
Randall Twede
Ranch Hand
Posts: 4481
3
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will compile as long as amethod of base class is anything but private. the problem is that private members are not inherited. therefore you are not overriding. and you cannot access the private(base class) method from outside the class it is declared in.
 
Michael Lin
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what I mean here is that b is actually pointing to the Abs object, it should have access to its own method. even though its class type is Base.
 
Bharatesh H Kakamari
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember one Thumb Rule for overriding. This is from Khalid's book. Terrific Book Indeed How did this author think this way
The rule says in the case of Overriding, the compiler seeks the actual Object being held by the reference. So the compiler will execute the method in Abs class which does not exists.
HTH
 
Rishi Singh
Ranch Hand
Posts: 321
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this case as the base class method is declared private, and as per the rule governing overriding, the compiler sees the actual object being pointed by the reference variable which in this case is of Abs class but the type of reference is of Base class, so it looks for a the method with a private acess specifier which is public in this case,try making the Abs method private it should work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic