final
public class Main {
public static void main(String[] args) {
People p = new People();
p.test();
}
}
class People{
final int i = 0;
final String s = "hello ";
final Car car = new Car("blue");
public void test(){
System.out.println("i = " + i + "Car color = " + car.getColor() + " hashcode: " + car.hashCode());
// i = 1;
// System.out.println("i = " + i + "Car color = " + car.getColor());
car.setColor("red");
System.out.println("i = " + i + "Car color = " + car.getColor() + " hashcode: " + car.hashCode());
}
}
class Car{
private String color;
public Car(String color){
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
/**
输出结果:
i = 0 Car color = blue hashcode: 1239731077
i = 0 Car color = red hashcode: 1239731077
*/
final修饰基本类型数据,数据为常量,不可修改值,修改会有如下提示。
final修饰对象,对象的引用不可变,对象的属性值可变。
static
public class Main {
static int i = 0;
int a = 0;
public static void main(String[] args) {
// System.out.println(a); // a不能被引用,static 修饰的方法会早于常规变量被加载。
System.out.println(i);
}
}
static方法只能调用static修饰的成员变量。
static属性/代码块优先于构造函数被初始化:
public class Main {
public static void main(String[] args) {
Employee e = new Employee(3);
Employee.test();
}
}
class Employee{
int a;
{
System.out.println("常规代码块");
}
static {
System.out.println("static代码块");
}
public Employee(int i){
System.out.println("构造方法调用");
a = i;
}
static int b = 0;
public static void test(){
System.out.println("静态方法调用");
b ++;
}
}
/**
执行结果为:
static代码块
常规代码块
构造方法调用
静态方法调用
*/
构造器
每个类创建都会默认有一个无参构造,但是当我们实现了构造器以后,默认的无参构造会失效。