private
private是用于封装。他能保证变量只能被该类访问,而不被外部的类访问。保证的数据的稳定 被private修饰的变量,他只能在初始化的时候 或者在该类的方法里面 进行赋值操作,在其他地方赋值是不被允许的 父类中的private子类也不可继承
public class test {
private int a = 1 ;
private int b = a;
public void increase{
a++;
}
}
public
能被位于同一个包 的所有 类访问,如果不是位于同一个包的,如果不添加impotr该包就不能访问
static
static变量 static变量不属于任何一个对象,他是被这个类定义的所有的对象共同使用的 static变量的初始化,与对象的创建时无关的
public class Display {
private int value = 0 ;
private int limit;
private static int step = 1 ;
public Display (int limit) {
this .limit = limit;
}
public int getValue () {
return value;
}
public void increase (){
value++;
}
public static void main (String[] args){
Display d1 = new Display(20 );
Display d2 = new Display(10 );
d1.increase();
System.out.println(d1.getValue());
System.out.println(d2.getValue());
System.out.println(d1.step);
System.out.println(d2.step);
d1.step = 2 ;
System.out.println(d1.step);
System.out.println(d2.step);
Display.step = 3 ;
System.out.println(d1.step);
System.out.println(d2.step);
}
}
static方法 目的:方便不构造对象来调用 static方法只能调用static方法、只能访问static变量,(可以通过具体的对象来访问static方法)但是,在非static方法中,能调用static方法和static变量
public class test {
private int a = 5 ;
private static int b = 4 ;
public static void e (){
a++;
b++;
f();
}
public void f (){
a++;
b++;
e();
}
public static void main (String[] args){
}
}
final
被final修饰的变量叫做静态常量,一旦把一个变量加了final后,他的值就不能被改变,无论什么情况
public class test {
final int a = 2 ;
private int b = 3 ;
a = 3 ;
a = b;
b = 4 ;
}
protected
自己可以访问,同一个包内的可以访问,子类也可以访问