Accessing public static variables inside a class declared private

Asked 2 years ago, Updated 2 years ago, 151 views

private class Example {
    public static final PI = 3.14;

    ...

}

If there is a code configuration like above, is PI accessible from the outside? Classers restrict access from the outside to private, but PI allows access from the outside, so in this situation, I don't know which access has the upper hand, or exceptions because it's static.

java private static

2022-09-22 19:43

1 Answers

Private is not available in the top class declaration.

If you think about it, there's no reason to create a class that you can't even approach as a matter of course. If so, when is the private (protected) class declaration lamp used?

It is used to create an inner class. You can restrict access to the inner class.

Analyze the example.

package yhjung;

public class MyClass {
    Private class InnerMyClass { // InnerClass is private and is only available in MyClass
        public InnerMyClass() {
            System.out.println(this.getClass().getName());
        }
        public String getName(){
            return this.getClass().getName();
        }
    }

    Public class Inner Class For Public { // accessible from the outside
        public InnerMyClassForPublic() {
            System.out.println(this.getClass().getName());
        }
        public String getName(){
            return this.getClass().getName();
        }
    }

    public void showInnerClassName() {
        InnerMyClass ic = new InnerMyClass();
        String icName = ic.getName();
        System.out.println(icName);
    }
}


package yhjung;
public class Main {
    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.showInnerClassName();

        MyClass.InnerMyClassForPublic mc2 = mc.new InnerMyClassForPublic();
        System.out.println(mc2.getName());
    }
}


yhjung.MyClass$InnerMyClass
yhjung.MyClass$InnerMyClass
yhjung.MyClass$InnerMyClassForPublic
yhjung.MyClass$InnerMyClassForPublic


2022-09-22 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.