JavaSE进阶:final修饰符

一.final修饰的类无法继承

示例:

public class TestFinal {
    
    
    public static void main(String args[]) {
    
    
    	
    }
}
final class TestA{
    
    
	
}
class TesrB extends TestA{
    
    
	
}

错误提示:
The type TesrB cannot subclass the final class TestA
final修饰的类为最终类,该类不能被子类继承重写。

二.final修饰的方法无法重写

示例:

public class TestFinalMethod {
    
    
    public static void main(String[] args) {
    
    
    	MethodB s1 = new MethodB();
    	s1.methodA();
    }
}
class MethodA{
    
    
	public final void methodA() {
    
    
		System.out.println("-----A-----");
	}
}
class MethodB extends MethodA{
    
    
	public void methodA() {
    
    
		System.out.println("-----B-----");
	}
}

错误提示:
Exception:inthread"main"java.VerifyError:class MethodB overrides final method MethodA.method()V
final修饰的方法无法重写。

三.final修饰的局部变量只能赋一次值

public class TestFinal2 {
    
    
	public static void main(String args[]) {
    
    
		final int a;
		a = 100;
		final int b = 100;
		b = 90;
	}

}

错误提示:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The final local variable b cannot be assigned. It must be blank and not using a compound assignment

final修饰的变量只能赋值一次。

四.final修饰的引用只能指向一个对象

public class Test1 {
    
    
    public static void main(String args[]) {
    
    
    	Person p1 = new Person(30);
    	p1 = new Person(40);
    	System.out.println(p1.age);
    }
}
class Person{
    
    
	int age;
	public Person() {
    
    
		
	}
	public Person(int age) {
    
    
		this.age = age;
	}
}

以上代码没有任何的问题,但是引用也是一个变量,只是它存储的是地址,所以我们想到如果我们在引用前加一个final会出现什么情况。

public class Test1 {
    
    
    public static void main(String args[]) {
    
    
    	final Person p1 = new Person(30);
    	p1 = new Person(40);
    	System.out.println(p1.age);
    }
}
class Person{
    
    
	int age;
	public Person() {
    
    
		
	}
	public Person(int age) {
    
    
		this.age = age;
	}
}

错误:
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The final local variable p1 cannot be assigned. It must be blank and not using a compound assignment

内存图如下:
在这里插入图片描述

五.final修饰的实例变量必须手动赋值

public class Test2 {
    
    
    public static void main(String args[]) {
    
    
    	
    }
}
class Person2{
    
    
	final int a;
}

错误:
The blank final field a may not have been initialized
我们改一下就不报错了。

final int a = 10;

六.常量

在五中,我们看到实例变量前面加入final后值不会发生变化,但是它是实例变量,实例变量在堆中,并且一个对象有一份,显然浪费内存,所以我们一般在final修饰的实例变量前面加入static,使得它变成常量,在方法区中,节约内存。

public class Test2 {
    
    
    public static void main(String args[]) {
    
    
    	
    }
}
class Person2{
    
    
	static final int a = 10;
}

常量一般是公开的,所以常量一般写成:

public static final int a = 10;

猜你喜欢

转载自blog.csdn.net/weixin_45965358/article/details/114501285