Darshan Parikh
Darshan Parikh

Reputation: 23

How to access a protected method of superclass in a subclass?

I have parent-child classes in two different packages. I am overriding a method of protected type. I want to access super class protected method in subclass.

Consider below code:

package package1;

public class Super
{
    protected void demoMethod()
    {
        System.out.println("In super method");
    }
}

package package2;

import package1.Super;

public class Sub extends Super
{
    @Override
    protected void demoMethod()
    {
        System.out.println("In sub method");
    }

    public static void main(String[] args) 
    {
        //code for accessing superclass demoMethod to print "In super method"
    }
}

In the main method of sub class, I want to access super class demoMethod which prints "In super method". I know demoMethod won't be visible from sub class using super class object reference to call demoMethod.

Is it possible or not? If yes, how?

Consider me new to Java and provide answers replacing comment in main method.

Upvotes: 2

Views: 6918

Answers (2)

Andy Thomas
Andy Thomas

Reputation: 86381

Your main() method cannot access the superclass implementation of demoMethod() -- because it's overridden in the child class.

Your main() method can access demoMethod(), through a reference of the subclass type, even though it's protected, because it's in the same package as your subclass. But it will call the subclass implementation.

But if you're "using superclass object reference to call demoMethod", the method will not be accessible, and your code will not compile. Your superclass is in a different package. Methods marked protected can only be accessed by subclasses and by code in the same package.

If you made the method public in both subclass and superclass, calling demoMethod() would call the subclass implementation, regardless whether the reference was of the super or subclass type.

An instance of the subclass can call super.demoMethod() as part of the implementation of its methods. But the main() method cannot.

Upvotes: 1

MaxPower
MaxPower

Reputation: 871

In the child class use super.demoMethod() or just remove it altogether from the child class

Upvotes: 2

Related Questions