Why am I able to call private method?

2020-03-05 02:01发布

I should not be able to invoke a private method of an instantiated object. I wonder why the code below works.

public class SimpleApp2 {
    /**
     * @param args
     */
    private int var1;

    public static void main(String[] args) {
        SimpleApp2 s = new SimpleApp2();
        s.method1(); // interesting?!
    }

    private void method1() {
        System.out.println("this is method1");
        this.method2(); // this is ok
        SimpleApp2 s2 = new SimpleApp2();
        s2.method2(); // interesting?!
        System.out.println(s2.var1); // interesting?!
    }

    private void method2() {
        this.var1 = 10;
        System.out.println("this is method2");
    }
}

I understand that a private method is accessible from within the class. But if a method inside a class instantiate an object of that same class, shouldn't the scope rules apply to that instantiated object?

Can static method like main access the non-static member of the class, as given in this example ?

标签: java core
8条回答
我欲成王,谁敢阻挡
2楼-- · 2020-03-05 02:41

Because main is also a member of SimpleApp.

查看更多
对你真心纯属浪费
3楼-- · 2020-03-05 02:47

From the Java Tutorial:

private modifier—the field is accessible only within its own class

The main method is inside the same class as the private method and thus has access to it.

查看更多
ら.Afraid
4楼-- · 2020-03-05 02:51

See below chart

Access Modifiers

                     **Same Class    Same Package   Subclass   Other packages**
**public**                Y               Y            Y              Y
**protected**             Y               Y            Y              N
**no access modifier**    Y               Y            N              N
**private**               Y               N            N              N

As your method is inside car it's accessible based on above thumb rule.

查看更多
乱世女痞
5楼-- · 2020-03-05 02:56

The call you issue is from within the same class where your private method resides. This is allowed. This is the way 'private' is defined in java.

查看更多
贼婆χ
6楼-- · 2020-03-05 02:56

In the program, we created two instances of the class by using which we called two private methods. It's a kind of interesting to see this works is that this is the way we used to call public or default methods outside its class using object reference. In this case, it's all done inside the class definition, so it's valid. The same code put outside the class will result in error.

查看更多
Animai°情兽
7楼-- · 2020-03-05 02:57

Because the private scope limits access to the class defining the method, and your main happens to be in the same class.

private modifier—the field is accessible only within its own class.

See Access Modifiers in the Java Documentation.

查看更多
登录 后发表回答