Private
1 is a permission modifier
2 You can modify member variables and member methods
Members that are modified by them can only be accessed in this class
1 classDemo {2 //int num = ten;3 //Decorate with private4 Private intnum = 10;5 6 Public voidShow () {7 System.out.println (num);8 }9 Ten Private voidmethod () { OneSystem.out.println ("Method"); A } - - Public voidfunction () { the method (); - } - } - + classPrivatedemo { - Public Static voidMain (string[] args) { +Demo d =NewDemo (); A //cannot method private member variable at //System.out.println (d.num); - d.show (); - //the private member method cannot be accessed - //D.method (); - d.function (); - } in}
Applications for encapsulation and private:
A: Modify the member variable with private
B: Improve the corresponding getxxx () and setxxx () methods
1 classStudent {2 //name3 PrivateString name;4 //Age5 Private intAge ;6 7 //Name Get value8 PublicString GetName () {9 returnname;Ten } One A //Name Setting Value - Public voidSetName (String N) { -Name =N; the } - - //Age Get Value - Public intGetage () { + returnAge ; - } + A //age-assigned value at Public voidSetage (inta) { -Age =A; - } - } - - //Test Class in classStudenttest { - Public Static voidMain (string[] args) { to //Create student Objects +Student s =NewStudent (); - the //using member variables * //Error: The private decoration, the outside world can not directly access the $ //System.out.println (s.name+ "---" +s.age);Panax NotoginsengSystem.out.println (S.getname () + "---" +s.getage ()); - the //Assigning a value to a member variable + //s.name = "Brigitte"; A //s.age =; the //assigning values by method +S.setname ("Brigitte"); -S.setage (27); $System.out.println (S.getname () + "---" +s.getage ()); $ } -}
Java Note 14 private