Is the public modifier redundant inside a package private class?

Coder-Man :

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?

Ph1llip2 :

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
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=99269&siteId=1
Recommended