Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
90 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...