Coder-Man
Coder-Man

Reputation: 2531

Is the public modifier redundant inside a package private class?

Suppose I have a class Test declared in Test.java in package com.test:

class Test {
    public void test() {

    }
}

I was wondering, isn't the public access-modifier for the method test() redundant here? Because intellij doesn't give me a hint saying that it is.

I thought it's not redundant only if the class Test contains public static void main(String[] args) {} Am I right or wrong?

Upvotes: 3

Views: 767

Answers (3)

Ph1llip2
Ph1llip2

Reputation: 151

It is not redundant. If you have some derivative classes then the modifier makes a huge difference. Consider the classes:

package ex.one

class Test {
    public void testPublic() {

    }

    void testPackage() {

    }    
}

and another class which derives the Test.class

package ex.one

public class TestDerivate extends Test {

    private void doSomething(){
        //legal
        testPublic();
        testPackage();
    }

}

Now when we have another class which derives TestDerivate.class then you can see a different behaviour on the methods. In this case this class has a public modifier.

package ex.two

public class TestDerivateInOtherPackage extends TestDerivate {
    public void test(){
         // legal
         testPublic();
         //illegal since it is only package visible
         testPackage();
    }

    @Override
    public void testPublic() {
        // still legal
    }

    @Override
    void testPackage() {
        // still illegal
    }

}

Upvotes: 5

Daniel Pryden
Daniel Pryden

Reputation: 60997

It's not redundant, because if you did have an object of type Test outside of the package, the public modifier could make the method visible even though the class itself is not.

In practice this is pretty rare. As one example, if you have another class Test2 (in the same package) which extended from Test and was itself a public class, then the public modifier or lack of it would affect whether code outside the package could invoke test() on objects of type Test2.

The other, more common case would be if Test implemented an interface; then the method would have to be public, likewise to allow the method itself to be visible outside the package, where the class itself may not be visible but the interface may be.

Upvotes: 0

Timothy Truckle
Timothy Truckle

Reputation: 15634

any class may implement an interface. The latter contains declarations of methods which are always public. Furthermore you cannot reduce the visibility of an interface method.

Therefore it must be possible to declare a public method within a non public class.

Upvotes: 1

Related Questions