Home >Java >JavaBase >Detailed explanation on how to use the final keyword in java

Detailed explanation on how to use the final keyword in java

王林
王林forward
2019-12-20 11:59:421931browse

Detailed explanation on how to use the final keyword in java

1. Modified class

A class modified by final cannot be inherited by subclasses.

//父类Animal
public final class Animal{
	private int age;  //年龄
	private String var;  //品种
	 public void eat(){
		 System.out.println("吃东西");
	 	}
	 }
	//子类cat
	public class cat extends Animal{   //编译时会报错,编译不通过。
		 public void eat(){
			 System.out.println("吃鱼");
	 	}
	}

Free online video tutorial recommendation: java video

2. Modify member methods

Member methods modified by final cannot be overridden.

	//父类Animal
public class Animal{
	private int age;  //年龄
	private String var;  //品种
	 public final void eat(){  //成员方法
		 System.out.println("吃东西");
	 	}
	 }
	//子类cat
	public cat extends Animal{    
		 public void eat(){   //重写父类方法。编译时会报错,编译不通过。
			 System.out.println("吃鱼");
	 	}
	}

3. Modify basic variable types

Variables modified by final can only be assigned once.

public class Animal{
	public static void main(String str){
		private int i = 10;
		i = 20;        //编译时,此处报错。
		System.out.println(i);
		}
	}

4. Modified reference variables

The modified reference variable can only point to the object once.

public class Animal{
	public static void main(String str){
		final Cat c;
		c = new Cat();
		c = new Cat();
		}
	}

public class Cat{
	private String var;
	private int age;
	public void eat(){
		System.out.println("吃鱼");
		}
	}

5. Modified constants

格式:public static final int I = 10;

Recommended related articles and tutorials: Getting started with java development

The above is the detailed content of Detailed explanation on how to use the final keyword in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete