2016.5.17 随笔————JAVA关键字 static private
一直以来对于 static private public概念不明确,今天好好整理一下:
1 package javaPractice; 2 3 public class staticExercise { 4 public static void main(String args[]){ 5 6 Person p1 = new Person("张三",30); 7 Person p2 = new Person("李四",20); 8 9 System.out.println("修改country 变量 之前"); 10 p1.printInfo(); 11 p2.printInfo(); 12 13 System.out.println("修改country变量之后"); 14 p1.setCountry("B城"); 15 p1.printInfo(); 16 p2.printInfo(); 17 System.out.println(p1.sex); 18 } 19 20 } 21 22 class Person{ 23 private String name; 24 private int age; 25 public String sex="男"; 26 private String country="A城"; 27 28 29 public Person(String name,int age){ 30 this.name=name; 31 this.age=age; 32 } 33 public void printInfo(){ 34 System.out.println("姓名:"+this.name+" 年龄:"+this.age+" 城市:"+country); 35 } 36 37 //country 的get、set方法 38 public String getCountry() { 39 return country; 40 } 41 public void setCountry(String country) { 42 this.country = country; 43 } 44 45 }
输出:
1. private 成员变量
私有成员变量只在本类中可用,
如何操作 如上述类Person 中的私有成员变量,,
其一 public 的构造方法 public Person(String name , int age){
this.name = name; this.age= age;}
其二 public 的 get set 方法;
2. static 全局变量
如果定义了 全局变量, 则意味着 在所有该类的对象中 , 共享 这个全局变量,一个变 全部变
比如 上面的结果图, 设定的是private String country变量
只改变量 p1.setCountry("B城"); 所以 p2 仍为 A城
那么 如果定义的是
则结果:
同样的原理, static 方法 是全局共享的方法,,
其中只能包含 static 声明的 变量!
执行一个static 方法 改变的 static 变量 即是全局性的。