Three usage notes for final keywords

Final English translation means final. The final keyword in Java can modify classes, methods, and variables.

  • The class modified by the final keyword cannot be inherited.
  • Methods modified by the final keyword cannot be overridden by subclasses.
  • Variables modified by the final keyword are constants and can only be assigned once.
    Example 1 (modification class):
//Animal类被final关键字修饰
public final class Animal {
    
    
    void show(){
    
    
        System.out.println("我是父类....");
    }
}
//Pig继承Animal,由于Animal被final关键字修饰,编译会不通过
public class Pig extends Animal {
    
    
//编译器提示Cannot inherit from final 'xxxxx.Animal',会编译不通过
}

    Example 2 (modified variable):

public class Example01 {
    
    
    public final String name = "小花";
    name = "小红";//再次为name赋值编译会报错
}

    It should be noted that when the final keyword is used to modify a member variable in a class, the virtual machine will not initialize the variable. Therefore, when the final keyword is used to modify the member variable, an initial value must be assigned when it needs to be defined.
    Example 3 (modification method)

//Animal类被final关键字修饰
public class Animal
    //show()方法使用final关键字修饰
    final void show(){
    
    
        System.out.println("我是父类....");
    }
}
public class Pig extends Animal{
    
    
    //编译会报错
    void show(){
    
    
        System.out.println(".....");
    }
}

When we write a program, if a method in the parent class does not want to be overridden by the subclass, we can use the final keyword to modify the method.
1024 Happy Holidays, come
on! ! !

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/109264610