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
*/

猜你喜欢

转载自blog.csdn.net/caigen0001/article/details/89710993