1. encapsulation features of classes:
Class encapsulation means that the class attributes are invisible to the outside, and the class methods can be used with restrictions. in my understanding, the encapsulated class has non-readable and non-writable attributes (getter and setter can be used for restricted read/write operations). The method can be called for read.
2. Class constructor:
The class constructor is the key part in 02, which is somewhat unfamiliar and takes more notes.
First, the class construction method is to initialize the class object attributes. The constructor has the same name as the class. It does not include the definition of the return value type and cannot use the return statement in the method body.
A class can contain one or more constructor methods. If a class does not explicitly define a constructorProgramA construction method without parameters is automatically generated during compilation;If the constructor has been clearly defined in the class, the constructor without parameters will not be automatically generated.
The constructor is used when an object is instantiated. During Object Instantiation, the constructor in the class is automatically called to initialize attributes in the class. Note that,If you use constructors to initialize object properties, it is best to call the geeter and setter methods.
The following is an example of how to use the constructor. The comments section describes the usage process and precautions:
Class person {// defines the property private string name; private int age of the class "person"; // defines the constructor public person () {} public person (string name, int age) {// If the constructor assigns a value to the attribute, it is best to use the getter and seter methods this. setname (name); this. setage (AGE) ;}// define the getter and setter Methods Public String getname () {return name;} public void setname (string N) {This. name = N;} public int getage () {return age;} public void setage (int A) {// prevent illegal age input if (a> 0 & A <150) {This . Age = A;} else {This. age =-1 ;}// define the method void say () {system. out. println ("My name is:" + name + ", my age is:" + (age> 0? Age: "illegal age! ") ;}} Public class classdemo01 {public static void main (string ARGs []) {// declared object: declared in stack memory; Class Name object name = NULL; // instantiate the object: Use new to open up space in the heap memory and save the object attributes; object name = New Class Name (); person P = new person ("Zhang San", 23 ); // pass object. method: Call the Method P of the object. say ();}}