Why am I able to call private method?

后端 未结 8 1465
深忆病人
深忆病人 2020-12-10 21:29

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         


        
相关标签:
8条回答
  • 2020-12-10 21:39

    private means "only stuff in this class can mess around with it". It doesn't mean "only this instance can call its methods", which seems to be what you're expecting. Any code in SimpleApp can use anything in any SimpleApp. The alternative would be to break encapsulation -- how would you make a proper equals method, for example, that didn't require access to another instance's fields, without making those fields protected or even public or requiring getters for data that should only be available inside the class?

    0 讨论(0)
  • 2020-12-10 21:39

    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.

    0 讨论(0)
  • 2020-12-10 21:41

    Because main is also a member of SimpleApp.

    0 讨论(0)
  • 2020-12-10 21:44

    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.

    0 讨论(0)
  • 2020-12-10 21:46

    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.

    0 讨论(0)
  • 2020-12-10 21:52

    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.

    0 讨论(0)
提交回复
热议问题