Java learning summary: 11

final keyword

Final is called a finalizer in Java, and final can be used to define classes, methods, and properties in Java.

1. Classes defined with final can no longer have subclasses, that is: no class can inherit the parent class declared with final.

final class A{	//此类不能够有子类
}
class B extends A{	//错误的继承
}

Note: String is also a class defined using final, so the String class is not allowed to be inherited.

2. The method defined by final cannot be overridden by subclasses.

class A{
	public final void fun(){//此方法不允许被子类覆写
	}
}
class B extends A{
	public void fun(){}	//	错误:此处允许覆写
}

3. Variables defined using final become constants. Constants must be set up at the time of definition and cannot be modified.

class A{
	final double GOOD=100.0;
	public final void fun(){
		GOOD=1.1;	//错误:不能够修改常量
	}
}
49 original articles published · 25 praised · 1538 visits

Guess you like

Origin blog.csdn.net/weixin_45784666/article/details/104279712