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

王林
Release: 2019-12-20 11:59:42
forward
1934 people have browsed it

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("吃鱼");
	 	}
	}
Copy after login

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("吃鱼");
	 	}
	}
Copy after login

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);
		}
	}
Copy after login

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("吃鱼");
		}
	}
Copy after login

5. Modified constants

格式:public static final int I = 10;
Copy after login

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!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template