java基础(14)---修饰符

一、final(不能修改)

使用final修饰变量定义:该变量一旦被初始化之后就不允许再被修改。

final关键字修饰成员变量:其值不能改变,必须进行初始化。

final修饰引用类型:一旦为其赋值,将不能够重新用来引用另一个对象,不过可以修改其引用对象的成员 变量。

final修饰成员变量:

public class YourClassNameHere {
  final String color;   // 如果后面没有在构造函数中初始化,则错误。
  final String color1 = "红色";  //正确,进行显示初始化
  String color2 = "蓝色";
  public YourClassNameHere(String color){
    this.color = color;
  }
  public static void main(String[] args) {
    String color = "黄色";
    YourClassNameHere test = new YourClassNameHere(color);
    System.out.println(test.color);
    String color1 = "绿色";
    YourClassNameHere test1 = new YourClassNameHere(color1);
    System.out.println(test1.color);
    System.out.println(test1.color1);
    
    // test1.color = "改变颜色"; //错误,不能修改final变量
    test1.color2 = "改变颜色2";
    System.out.println(test1.color2);
    }
}
知识兔

final修饰的局部变量:

final修饰局部变量可以只声明不初始化,但是被修饰的局部变量一旦被赋值后就不能进行修改了。如果在创建时没有对其赋值,那么在使用前还是可以对其赋值的。

final修饰的方法:

被修饰的方法能被该类的子类所继承,但不能重写,这样保护了父类某些特殊的数据。

//重写父类方法,但没有用final修饰
class bike
{
    String color = "黄色";
    
    public void getMes()
    {
        System.out.println("父类的成员变量color" + color);
    }
}
public class test extends bike
{
    String color = "绿色";

    //重写父类方法
    public void getMes()
    {
        System.out.println("子类的成员变量color" + color);
    }
    public static void main(String[] args)
    {
        test t = new test();
        t.getMes();
        
    }
}    
知识兔
//重写父类方法,用final修饰
class bike
{
    String color = "黄色";
    
    public final void getMes()
    {
        System.out.println("父类的成员变量color" + color);
    }
}
public class test extends bike
{
    String color = "绿色";

    //不能重写父类方法
/*
    public void getMes()
    {
        System.out.println("子类的成员变量color" + color);
    }
*/
    public static void main(String[] args)
    {
        test t = new test();
        t.getMes();
        
    }
}    
知识兔

二、static(只能存一份)

静态:在内存中只能有一份。

静态变量:只能存在一份,它属于类,不属于对象,不随着对象的创建而建立副本。如果不想在创建对象的时候就需要知道一些相关信息,那么就声明为static类型。

public class test
{
    static String color = "绿色";
    
    public test(String color)
    {
        this color += color;
    }

    public static void main(String[] args)
    {
        test t1 = new test("黄色");
        test t2 = new test("红色");

        System.out.println(t1.color);  // 绿色黄色红色
        System.out.println(t2.color);  //绿色黄色红色
        System.out.println(color);  //绿色黄色红色
    }
}
知识兔

静态变量的访问:

  •   类名.静态成员变量名称
  •   静态成员变量名称

三、静态常量 static final 

静态常量:唯一的、不可变的、只存在一份的数据。系统不会分配默认值,必须初始化。

  • static:属于类,随着类的创建而创建。
  • final:值不能改变。
  • static和final没有先后之分。
计算机