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: 4092
1
posted
0
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
Michael Lin
Ranch Hand
Joined: Dec 04, 2000
Posts: 31
posted
0
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
posted
0
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
posted
0
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.