Java study notes-keyword final

1.final is a keyword in the Java language
2.final means final, immutable
3.final modified class cannot be inherited
4.final modified method cannot be overwritten
5.final modified variable: can only be assigned once value

//final修饰类
final class A{
	
}
class B extends A{
	
}
//final修饰方法
class C{
	public final void doSome(){
		System.out.println("C doSome");
	}
}
class D extends C{
	public void doSome(){
		System.out.println("D doSome");
	}
}
public class Test{
	public static void main(String[] args){
		B b = new B();
		D d = new D();
		d.doSome();
		//final 修饰局部变量
		final int i;
		i = 10;
		final int j = 100;
		j = 300;
	}
}


6. For references, after the final modified reference points to object A, it can no longer point to object B, but the data inside object A can be modified.
7. The final modified instance variable must be manually assigned (meaning of manual assignment: assignment after variable, assignment by constructor)

  • If the instance variable is not manually assigned, the system will assign a default value
  • And final modified variables: can only be assigned a value
  • Therefore, the final modified instance variable, regardless of the default value assigned by the system, requires the programmer to manually assign the value
  • Obviously Java designers are reluctant to bear this pot.
  • Manual assignment: There are two ways to write directly and construct in the syntax, but they are all assigned when the object is created
class User{
	//final修饰实例变量
	//会报错,没有为age赋值
	//final int age;
	final double height = 1.8;
	final double weight;
	
	//在构造方法中为finalx修饰的实例变量赋值会报错吗?
	public User(){
		weight = 90;
	}
}

Review: Instance variables are assigned when the object is created.
So both height and weight are assigned initial values ​​when a User object is created


8.final modified instance variable means that this variable will not change with the change of the object,
so conclusion: final modified instance variable, generally add static declaration as static variable to save memory.
Ultimate conclusion: static final joint declared variable is called " "Constant", constant names are recommended to be capitalized, and each word is underlined

class Chinese{
	String id;
	String name;
	static final String COUNTRY = "中国";
}

Guess you like

Origin www.cnblogs.com/zy200128/p/12708407.html
Recommended