Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract Class - Why is my protected method publicly accessible?

Tags:

java

Why can I access the doStuff() Method in the main method below? Since doStuff() is protected, I would expect that only TestClassImplementation has access to it.

public abstract class AbstractTestClass {
    protected void doStuff()
    {
        System.out.println("doing stuff ...");
    }
}

public class TestClassImplementation extends AbstractTestClass{

}

public class MyProgram {
    public static void main(String[] args) {
        TestClassImplementation test = new TestClassImplementation();
        test.doStuff(); //why can I access the doStuff() Method here?
    }
}
like image 509
marius2k12 Avatar asked Oct 06 '13 15:10

marius2k12


People also ask

Can we declare protected method in abstract class?

Yes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.

Is abstract method always public?

abstract methods have the same visibility rules as normal methods, except that they cannot be private .

Can protected method be accessed?

Protected Access Modifier: Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces.

Can we declare protected method in public class?

Notes: You cannot declare a class as protected . Only the methods or fields within a class can have this access modifier.


1 Answers

Looks like MyProgram class is in the same package of your AbstractTestClass. If so, then it can access to protected and public members of the classes in the same package.

Covered in Java tutorials:

Modifier    Class Package Subclass   World
public      Y     Y       Y          Y
protected   Y     Y       Y          N
no modifier Y     Y       N          N
private     Y     N       N          N

In order to fix this, just move the AbstractTestClass to another package. Similar for other relevant classes.

More info:

  • Controlling Access to Members of a Class
like image 59
Luiggi Mendoza Avatar answered Sep 22 '22 20:09

Luiggi Mendoza