*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why the overriding not working??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why the overriding not working???" Watch "why the overriding not working???" New topic
Author

why the overriding not working???

Michael Lin
Ranch Hand

Joined: Dec 04, 2000
Posts: 31
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

Joined: Oct 21, 2000
Posts: 4340
    
    2

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.


SCJP
Visit my download page
Michael Lin
Ranch Hand

Joined: Dec 04, 2000
Posts: 31
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

Joined: Nov 09, 2000
Posts: 198
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

Joined: Dec 09, 2000
Posts: 321
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why the overriding not working???
 
Similar Threads
[B] a private final method can be overridden!!!! [/B]
Marcus G exam 1 -58,59
Overloaded methods
Doubt in Mock Question
Overloading