/*private: is a permission modifier that modifies member variables and member methods that are decorated by members that can only be accessed in this class */class Demo {//int num = 10;//with private private int num = 10;public void Show () {System.out.println (num);} private void Method () {System.out.println ("method");} public void function () {method ();}} Class Privatedemo {public static void main (string[] args) {Demo d = new Demo ();//cannot method private member variable//SYSTEM.OUT.PRINTLN (D.num); D.show ();//cannot access private member methods//D.method ();d. function ();}}
/* Package and Private application: A: Use the member variable with private modifier B: Improve the corresponding getxxx () and Setxxx () methods *///define student class class student {// name private String name;// Age private int age;// Name get value Public string getname () {return name;} Name setting value Public void setname (String n) {name = n;} Age gain Value public int getage () {return age;} Age Assignment Public void setage (int a) {age = a;}} Test class Class studenttest {public static void main (String[] args) {// Create student Object Student s = new student ();// use member variable// error: Private decoration, the outside world can not directly access the// System.out.println (s.name+ "---" +s.age); System.out.println (S.getname () + "---" + s.getage ());// assign a value to a member variable// s.name = "Brigitte";// s.age = 27;// assigns S.setname ("Brigitte") by means of the method; S.setage (27); System.out.println (S.getname () + "---" + s.getage ());}}
Overview and features of the 4.9 private keyword