The encapsulation of classes is not only reflected in the encapsulation of attributes, but can also be encapsulated. Of course, the encapsulation of constructor methods is also included in the encapsulation of methods. The following code encapsulates the constructor.
The Code is as follows:
Class testclass {private testclass () {system. Out. println ("constructor is encapsulated! ");} Public void print () {system. Out. println (" method in the class! ") ;}} Public class testdemo {testclass Tc = NULL; // you can declare the object Tc = new testclass (); // It cannot be instantiated because the constructor is encapsulated, the instantiation method is equivalent to calling the constructor .}
The following error occurs during program Compilation:
Testdemo. Java: 6: Error: testclass () can access private in testclass
TC = new testclass ();
So how can we solve this problem?
Encapsulation means that everything is invisible to the outside, that is, it means that the outside cannot be called at all. Since the outside cannot be called, what about the inside of the class?
The instance code is as follows:
Class testclass {testclass Tc = new testclass (); Private testclass () {system. Out. println ("constructor is encapsulated! ");} Public void print () {system. Out. println (" method in the class! ") ;}} Public class testdemo {public static void main (string [] ARGs) {system. Out. println (" Hello! ");}}
The compilation result is as follows:
There is no compilation error, but the constructor is not called. How can this problem be called?
You know the static keyword. The method modified by static can be called using the class name.
The Code is as follows:
Class testclass {static testclass Tc = new testclass (); Private testclass () {system. Out. println ("constructor is encapsulated! ");} Public void print () {system. Out. println (" method in the class! ") ;}} Public class testdemo {public static void main (string [] ARGs) {testclass TT = NULL; TT = testclass. TC; // pass the object tc to the object tt, that is, the constructor is called, TT. print (); system. out. println ("Hello! ");}}
Running result: