Class members declared summary: public, friendly, private, protected

zhaozj2021-02-16  50

I have learned Java for two years, and suddenly I found my own public, friendly, private, protected, and opened "Thinking in Java Se" ... Summary: public: Data member and member of public as public Methods can be used by all client programmers. Friendly: For all classes in the same package, if two classes are placed in the same directory, but no declaration package, Java will think that these two classes belong to the same package, namely Friendly data members, and member methods available. Private: Cannot be seen for the outside world, can only be called within the class. In order to achieve the principle of Java "hidden implementation details", it is generally declared to Private. If the constructor is declared as Private, the client-side programmer cannot generate the objects of such a class, which can only generate the object of the class by the STATIC method provided. Is this "factory model" in "design mode"? Example: Public class a {private static makea ()} public static makea () {return new a ();} public static void main (String [] args) {///! ~ A = new a (); error, Can't use new to create an Object a a a = a.makea ();}} protected: A member of FRIENDLY can only be called in the same package, if you want a class inherits the class in another package And you can call the data member and members of this class, you need to declare these data members and members' methods as protected. For classes in the same package, the protected role is equivalent to Friendly.

转载请注明原文地址:https://www.9cbs.com/read-21625.html

New Post(0)