1. Java Static和Final使用总结

时间:2023-03-09 16:02:41
1. Java Static和Final使用总结

static:用于属性和方法

static修饰属性:无论一个类生成多少对象,所有这些对象共用唯一一个静态成员变量。一个对象对该静态变量进行修改,其他对象对该静态变量的值也随之发生变化。可以通过类名.成员变量名的方式来使用它。

static修饰方法:静态方法不能被重写,只能被隐藏。子类只能继承父类的静态方法,不能重写父类静态方法,子类隐藏了父类的静态方法。静态方法可以包含静态和非静态方法,非静态方法只能包含非静态方法,不能包含静态方法。

instance method:

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

static method:

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

The distinction between hiding a static method and overriding an instance method has important implications:

  • The version of the overridden instance method that gets invoked is the one in the subclass.
  • The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.

参考:http://docs.oracle.com/javase/tutorial/java/IandI/override.html

静态代码块:类加载到Java虚拟机上会执行静态代码块内容。先执行父类的静态代码块,然后依次执行子类静态代码块,最后在执行父类构造方法和子类构造方法。

类加载先执行静态代码块,然后执行构造方法

不能在静态方法中访问非静态成员变量。不能再静态方法中使用this关键字

final修饰类:表示该类是最终类,不能被继承。

final修饰方法:表示该方法是最终方法,不能被重写。

final修饰属性:表示该属性不能被改写。

final修饰原生类型时,原生类型的值不能发生变化。

final修饰引用类型时,表示该引用类型不能再指向其他对象,但引用对象的内容可以发生变化。

final成员变量赋值方式:

1. 声明final成员变量时就赋初值。

2. 在所有的构造方法中赋值。