Java——final修饰类,方法,变量特点

final可以修饰类,方法,变量。

  • final修饰的类不可以被继承。
  • final修饰的方法不可以被覆盖。
  • final修饰的变量是一个常量,只能被赋值一次。
  • 内部类只能访问被final修饰的局部变量(JDK8之前)。

 

//final修饰的类不可以被继承
final class Person
{
	String name;
	int age;
	
	void show()
	{
		System.out.println("person...");
	}
}

class Student extends Person //子类无法继承被final修饰的父类
{
	void study()
	{
		System.out.println("study...");
	}
}

public class FinalClass
{
	public static void main(String[] args)
	{
		Student s = new Student();
		s.study();
	}
}
/*
Exception in thread "main" java.lang.Error: 无法解析的编译问题:
	类型 Student 不能成为终态类 Person 的子类
*/

 

//final修饰方法不能被覆写
class Person
{
	String name;
	int age;
	
	final void show()
	{
		System.out.println("person...");
	}
}

class Student extends Person
{
	void show() //final修饰的方法不能被覆写
	{
		System.out.println("student...");
	}
}

public class FinalClass
{
	public static void main(String[] args)
	{
		Student s = new Student();
		s.study();
	}
}
/*
Exception in thread "main" java.lang.VerifyError: 
class Student overrides final method show.()
*/

 

//final修饰的变量只能赋值一次
class Person
{
	String name;
	final int AGE = 24;
	
	void show()
	{
		System.out.println("person...");
	}
}

class Student extends Person
{
	void show()
	{
		System.out.println("student...");
	}
}

public class FinalClass
{
	public static void main(String[] args)
	{
		Student s = new Student();
		s.AGE = 20; //final变量重复赋值
		s.show();
	}
}
/*
Exception in thread "main" java.lang.Error: 无法解析的编译问题:
	不能对final字段 Person.AGE 赋值
*/

 

//内部类只能访问被final修饰的局部变量
class Person 
{
	String name;
	int age;
	
	void display()
	{
		int x = 10; //JVM隐式添加final,不初始化会报错
		class Inner
		{
			void show()
			{
                           //x = 5;//出错,final变量不能重复赋值
				System.out.println(x);
			}
		}
		new Inner().show();
	}
}

public class InnerFinal
{
	public static void main(String[] args)
	{
		Person p = new Person();
		p.display();
	}
}
/*
//局部内部类(定义在方法中的内部类)Inner中的show()访问了外部类中的局部变量x。
//这里x并没有用final修饰(1.8之后java隐式的将x修饰为final)
10
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值