为什么我可以调用私有方法? [英] Why am I able to call private method?

查看:90
本文介绍了为什么我可以调用私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不应该能够调用实例化对象的私有方法。我想知道为什么下面的代码有效。

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?

像main这样的静态方法可以访问非对象吗?类的静态成员,如本例所示?

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

推荐答案

您的 main 方法是 SimpleApp 的方法,因此它可以调用 SimpleApp 的私有方法。

Your main method is a method of SimpleApp, so it can call SimpleApp's private methods.

只是因为它是静态方法并不能阻止它表现为 public目的的方法 private 等。 private 仅阻止 other 类访问 SimpleApp 的方法。

Just because it's a static method doesn't prevent it behaving like a method for the purposes of public, private etc. private only prevents methods of other classes from accessing SimpleApp's methods.

这篇关于为什么我可以调用私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆