java 示例_Java最终关键字示例

java 示例

The final keyword in Java can be used with variables, methods, and classes.

Java中的final关键字可以与变量,方法和类一起使用。

  1. Final Variables: When we mark a variable as final, we can’t reassign its value.

    最终变量 :将变量标记为最终变量时,我们无法重新分配其值。
  2. Final Class: When a class is final, we can’t extend it.

    最后一堂课:当最后一堂课时,我们不能扩展它。
  3. Final Method: We can’t override a final method.

    最终方法 :我们无法覆盖最终方法。

Let’s look into the final keyword in more details.

让我们更详细地研究final关键字。

Recommended Read: 推荐阅读Java Keywords Java关键词

1.最终变量 (1. Final Variables)

Java allows us two ways to create a variable and assign some value to it.

Java提供了两种创建变量并为其分配值的方法。

  1. We can declare a variable and assign the value later on.

    我们可以声明一个变量并稍后分配值。
  2. We can declare the variable and assign the value in the same statement using the assignment operator.

    我们可以使用赋值运算符在同一条语句中声明变量并赋值。

Let’s look at the usage of final variables for both the scenarios.

让我们看一下这两种情况下最终变量的用法。

package com.journaldev.examples;

public class Config {

	final static String NAME = "CONFIG";

	final long initTime;

	Config() {
		this.initTime = System.currentTimeMillis();
	}

	public static void main(String[] args) {
		Config cfg1 = new Config();
		System.out.println(cfg1.initTime);

		Config cfg2 = new Config();
		System.out.println(cfg2.initTime);

		// The final field Config.NAME cannot be assigned
//		Config.NAME = "config";

		// The final field Config.initTime cannot be assigned
//		cfg1.initTime = 1L;
	}
}

1.1)Java最终变量是常量吗? (1.1) Java Final Variables are Constant?)

Since we can’t reassign a new value to the final variable, they look like constant. But, it depends on the type of the final variable.

由于我们无法将新值重新分配给最终变量,因此它们看起来像常量。 但是,这取决于最终变量的类型。

If the final variable data type is immutable, such as primitives and String, then the final variable will remain constant.

如果最终变量数据类型是不可变的,例如基元和字符串,那么最终变量将保持不变。

If the final variable data type is mutable, we can call the methods to change the object state. In this case, the final variable is not constant as it can be changed.

如果最终变量数据类型是可变的,则可以调用方法来更改对象状态。 在这种情况下,最终变量不是恒定的,因为可以更改。

Let’s understand this with a simple example.

让我们用一个简单的例子来理解这一点。

package com.journaldev.examples;

public class FinalExamples {

	// data types are immutable
	final static int COUNT = 10;
	final static String NAME = "FinalExamples";
	
	// data types are mutable
	final static StringBuilder SB = new StringBuilder();
	
	public static void main(String[] args) {
		SB.append("Hello");
		System.out.println(SB.toString());
		
		SB.append("Java");
		System.out.println(SB.toString());

	}
	
}

1.2)局部最终变量 (1.2) Local Final Variables)

When a final variable is created inside a method, it’s called a local final variable.

在方法内部创建最终变量时,它称为局部最终变量。

void foo(int[] ints) {
	final int x = 10;
	final boolean flag;
	flag = true;

	for (final int i : ints) {
		System.out.println(i);
	}
}

We are able to use the final keyword in the enhanced for loop because when the for loop iteration is finished, a new variable is created every time. The same is not true with the normal for loop, so the below code will throw compile-time error.

我们能够在增强的for循环中使用final关键字,因为当for循环迭代完成时,每次都会创建一个新变量。 对于普通的for循环而言,情况并非如此,因此以下代码将引发编译时错误。

// The final local variable j cannot be assigned. 
// It must be blank and not using a compound assignment
for(final int j = 0; j< ints.length; j++) {
	System.out.println(j);
}

2.期末班 (2. Final Class)

When a class is declared as final, we can't extend it. It's called a final class. The perfect example of the final class in JDK is the String class.

当一个类声明为final时,我们不能扩展它。 这被称为最后一堂课。 JDK中最后一个类的完美示例是String类。

If you have to create an immutable class, you have to mark it as a final class.

如果必须创建一个不可变的类,则必须将其标记为最终类。

final class SecureAccess{
	
}

//compile time error
//class MoreSecureAccess extends SecureAccess {}
Java Final Class

Java Final Class

Java最终课程

3.最终方法 (3. Final Methods)

When a method is marked as final, it's called a final method. A final method can't be overridden in the subclass. For example, Object class wait() and notify() methods are final and we can't override them in our implementation classes.

当一个方法被标记为final方法时,它称为final方法。 最终方法不能在子类中覆盖。 例如,对象类的wait()和notify()方法是最终的,我们不能在实现类中覆盖它们。

Overloading is allowed for the final methods. Let's look at an example of final methods in Java.

最终方法允许重载。 让我们看一下Java中最终方法的示例。

package com.journaldev.examples;

public class Base {
	
	final void foo(int i) {}
	
	//overloading is allowed
	void foo(int i, String s){}
}

class Child extends Base{
	
	@Override
	void foo(int i, String s) {}
	
	@Override
	// void foo(int i) {}
}
Java Final Method

Java Final Method

Java Final方法

4.何时在Java中使用final关键字? (4. When to use final keyword in Java?)

  • We can use final keyword to define some class level constants.

    我们可以使用final关键字定义一些类级别的常量。
  • Create final variables for objects when you don't want them to be changed, such as Object specific properties that we can use for logging purposes.

    当您不想更改对象时,请为其创建最终变量,例如可用于记录目的的特定于对象的属性。
  • If you don't want the class to be extended, mark it as final.

    如果您不希望扩展该类,请将其标记为final。
  • If you are creating an immutable class, you have to make it a final class.

    如果要创建一个不可变的类,则必须将其设为最终类。
  • If you want the method implementation to remain same for all the subclasses, mark them as a final method.

    如果您希望所有子类的方法实现都保持不变,则将它们标记为最终方法。

5.参考 (5. References)

翻译自: https://www.journaldev.com/33236/java-final-keyword-examples

java 示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值