File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why the overriding not working???" Watch "why the overriding not working???" New topic

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){
class Abs extends Base{

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

public void amethod(int iOver){
//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?
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4351

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.

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.
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:
subject: why the overriding not working???
It's not a secret anymore!