Search code examples
javapolymorphism

Polymorphism - access specifier changed in derived class


Hi I just wanted to undertand the following behavior.. I have defined the same method - gg() in the base and derived class with different access

Class Base  
{  
// some thing   
**private** Integer gg(){  
 //return something   
 }  
}

Class Derived{  
// something  
**public** Integer gg(){  
//return something  
}  
}

In my main method when I initialize a variable

  Base d = new Derived()  

and attempt to call d.gg() it says Base.gg() is private. Does modifying the access specifier make the method calls revert to the Base class method?. When i change the access specifer of gg() in base class to public, then it calls the method in Derived class just as polymorphism should.

From what I read about polymorphism, its ok to make the access specifier less restrictive in derived class which was the case here .


Solution

  • Accessing an object through a reference-to-base-class means that you intend to access it via the interface specified by the base class. If you've declared a method private in the base class, then you can't access it via a reference-to-base!

    Consider the absurdity that would ensue if that weren't the case:

    Base b;
    
    if (some condition) {
        b = new Base();
    }
    else {
        b = new Derived();
    }
    
    b.ggg();  // Ok, or not?