[个人笔记] Java的修饰符

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);
    }
}
/*
 * 输出
 * 1 d1 value
 * 0 d2 value
 * 1 d1 step
 * 1 d2 step
 * 2 修改d1.step后d1 setp
 * 2 修改d1.step后d2 setp
 * 3 修改display.step后d1 setp
 * 3 修改display.step后d2 setp
 */
  • 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++; //wrong
        b++; //true
        f(); //wrong
    }

    public void f(){
        a++; //true
        b++; //true
        e(); //true
    }

    public static void main(String[] args){

    }
}

final

  • 被final修饰的变量叫做静态常量,一旦把一个变量加了final后,他的值就不能被改变,无论什么情况
public class test{
    final int a = 2;
    private int b = 3;

    a = 3; //wrong
    a = b; //wrong

    b = 4; //true
}

protected

  • 自己可以访问,同一个包内的可以访问,子类也可以访问

猜你喜欢

转载自blog.csdn.net/a1203991686/article/details/81181001