简体   繁体   中英

Recursive object access to private methods

Why does the following code print "YO"? Whose printYo() is being called? I would think that this code would not compile because printYo() is private to t .

public class Test {
    private void printYo() {
        System.out.println("YO");
    }

    public void doubleTrouble(Test t) {
        t.printYo();
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.doubleTrouble(new Test());
    }
}

What can I do to make sure the outer object doesn't mutate the argument class?

printYo() is private to t

No. That method is private in regards to the class Test . Any piece of code within Test can use it.

What can I do to make sure the outer object doesn't mutate the argument class?

Java does not have any built in mechanism to refuse access to members on a per instance basis. (If that is what you meant.)

You are calling the method with in the class , which sound correct for the output . Even if you call the main method from different class it gives the same output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM