java final keyword

本文详细探讨了Java中final关键字的多种用途,包括final变量、final方法、final类等,展示了final如何用于锁定变量值、阻止方法重写、防止类继承,以及在效率优化方面的历史角色。

case 1: final data

// reuse/FinalData.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// The effect of final on fields

import java.util.*;

class Value {
  int i; // Package access

  Value(int i) {
    this.i = i;
  }
}

public class FinalData {
  private static Random rand = new Random(47);
  private String id;

  public FinalData(String id) {
    this.id = id;
  }
  // Can be compile-time constants:
  private final int valueOne = 9;
  private static final int VALUE_TWO = 99;
  // Typical public constant:
  public static final int VALUE_THREE = 39;
  // Cannot be compile-time constants:
  private final int i4 = rand.nextInt(20);
  static final int INT_5 = rand.nextInt(20);
  private Value v1 = new Value(11);
  private final Value v2 = new Value(22);
  private static final Value VAL_3 = new Value(33);
  // Arrays:
  private final int[] a = {1, 2, 3, 4, 5, 6};

  @Override
  public String toString() {
    return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5;
  }

  public static void main(String[] args) {
    FinalData fd1 = new FinalData("fd1");
    // - fd1.valueOne++; // Error: can't change value
    fd1.v2.i++; // Object isn't constant!
    fd1.v1 = new Value(9); // OK -- not final
    for (int i = 0; i < fd1.a.length; i++) {
      fd1.a[i]++; // Object isn't constant!
    } // - fd1.v2 = new Value(0); // Error: Can't
    // - fd1.VAL_3 = new Value(1); // change reference
    // - fd1.a = new int[3];
    System.out.println(fd1);
    System.out.println("Creating new FinalData");
    FinalData fd2 = new FinalData("fd2");
    System.out.println(fd1);
    System.out.println(fd2);
  }
}
/* Output:
fd1: i4 = 15, INT_5 = 18
Creating new FinalData
fd1: i4 = 15, INT_5 = 18
fd2: i4 = 13, INT_5 = 18
*/

Note the output show i4 are unique, INT_5 is not changed.

case 2: blank finals

// reuse/BlankFinal.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// "Blank" final fields

class Poppet {
  private int i;

  Poppet(int ii) {
    i = ii;
  }
}

public class BlankFinal {
  private final int i = 0; // Initialized final
  private final int j; // Blank final
  private final Poppet p; // Blank final reference
  // Blank finals MUST be initialized in constructor:
  public BlankFinal() {
    j = 1; // Initialize blank final
    p = new Poppet(1); // Init blank final reference
  }

  public BlankFinal(int x) {
    j = x; // Initialize blank final
    p = new Poppet(x); // Init blank final reference
  }

  public static void main(String[] args) {
    new BlankFinal();
    new BlankFinal(47);
  }
}

You’re forced to perform assignments to finals either with an expression at the point of definition of the field or in every constructor.

case 3: final arguments

// reuse/FinalArguments.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using "final" with method arguments

class Gizmo {
  public void spin() {}
}

public class FinalArguments {
  void with(final Gizmo g) {
    // - g = new Gizmo(); // Illegal -- g is final
  }

  void without(Gizmo g) {
    g = new Gizmo(); // OK -- g not final
    g.spin();
  }
  // void f(final int i) { i++; } // Can't change
  // You can only read from a final primitive:
  int g(final int i) {
    return i + 1;
  }

  public static void main(String[] args) {
    FinalArguments bf = new FinalArguments();
    bf.without(null);
    bf.with(null);
  }
}

case 4: final methods

There are two reasons for final methods. The first is to put a “lock” on the method to prevent an inheriting class from changing that method’s meaning by overriding it.

The second reason final methods were suggested in the past is efficiency. In earlier implementations of Java, if you made a method final , you allowed the compiler to turn any calls to that method into inline calls. When the compiler saw a final method call, it could (at its discretion) skip the normal approach of inserting code to perform the method call mechanism (push arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value) and instead replace the method call with a copy of the actual code in the method body. This eliminates the overhead of the method call. However, if a method is big, your code begins to bloat, and you probably wouldn’t see performance gains from inlining, since any speedups in the call and return were dwarfed by the amount of time spent inside the method. Relatively early in the history of Java, the virtual machine (in particular, the hotspot technologies) began detecting these situations and optimizing away the extra indirection. For a long time, using final to help the optimizer has been discouraged. You should let the compiler and JVM handle efficiency issues and make a method final only to explicitly prevent overriding.

ps: please note the comments in the code.

case 5: final and private

Any private methods in a class are implicitly final.

// reuse/FinalOverridingIllusion.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// It only looks like you can override
// a private or private final method

class WithFinals {
  // Identical to "private" alone:
  private final void f() {
    System.out.println("WithFinals.f()");
  }
  // Also automatically "final":
  private void g() {
    System.out.println("WithFinals.g()");
  }
}

class OverridingPrivate extends WithFinals {
  private final void f() {
    System.out.println("OverridingPrivate.f()");
  }

  private void g() {
    System.out.println("OverridingPrivate.g()");
  }
}

class OverridingPrivate2 extends OverridingPrivate {
  public final void f() {
    System.out.println("OverridingPrivate2.f()");
  }

  public void g() {
    System.out.println("OverridingPrivate2.g()");
  }
}

public class FinalOverridingIllusion {
  public static void main(String[] args) {
    OverridingPrivate2 op2 = new OverridingPrivate2();
    op2.f();
    op2.g();
    // You can upcast:
    OverridingPrivate op = op2;
    // But you can't call the methods:
    // - op.f(); // error: f() has private access in OverridingPrivate
    // - op.g(); // error: g() has private access in OverridingPrivate
    // Same here:
    WithFinals wf = op2;
    // - wf.f(); // error: f() has private access in WithFinals
    // - wf.g(); // error: g() has private access in WithFinals
  }
}
/* Output:
OverridingPrivate2.f()
OverridingPrivate2.g()
*/

If a method is private , it isn’t part of the base-class interface. It is just code that’s hidden away inside the class, and it just happens to have that name. But if you create a public, protected, or package-access method with the same name in the derived class, there’s no connection to the method that might happen to have that name in the base class. You haven’t overridden the method, you’ve just created a new method.

case 6: final classes

It prevents inheritance.

// reuse/Jurassic.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Making an entire class final

class SmallBrain {}

final class Dinosaur {
  int i = 7;
  int j = 1;
  SmallBrain x = new SmallBrain();

  void f() {}// implicicitly final
}

// - class Further extends Dinosaur {}
// error: Cannot extend final class 'Dinosaur'

public class Jurassic {
  public static void main(String[] args) {
    Dinosaur n = new Dinosaur();
    n.f();
    n.i = 40;
    n.j++;
  }
}

Be caution when make a method final.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/FinalData.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/BlankFinal.java

4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/FinalArguments.java

5. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/FinalOverridingIllusion.java

6. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/Jurassic.java

源码来自:https://pan.quark.cn/s/a3a3fbe70177 AppBrowser(Application属性查看器,不需要越狱! ! ! ) 不需要越狱,调用私有方法 --- 获取完整的已安装应用列表、打开和删除应用操作、应用运行时相关信息的查看。 支持iOS10.X 注意 目前AppBrowser不支持iOS11应用查看, 由于iOS11目前还处在Beta版, 系统API还没有稳定下来。 等到Private Header更新了iOS11版本,我也会进行更新。 功能 [x] 已安装的应用列表 [x] 应用的详情界面 (打开应用,删除应用,应用的相关信息展示) [x] 应用运行时信息展示(LSApplicationProxy) [ ] 定制喜欢的字段,展示在应用详情界面 介绍 所有已安装应用列表(应用icon+应用名) 为了提供思路,这里只用伪代码,具体的私有代码调用请查看: 获取应用实例: 获取应用名和应用的icon: 应用列表界面展示: 应用列表 应用运行时详情 打开应用: 卸载应用: 获取info.plist文件: 应用运行时详情界面展示: 应用运行时详情 右上角,从左往右第一个按钮用来打开应用;第二个按钮用来卸载这个应用 INFO按钮用来解析并显示出对应的LSApplicationProxy类 树形展示LSApplicationProxy类 通过算法,将LSApplicationProxy类,转换成了字典。 转换规则是:属性名为key,属性值为value,如果value是一个可解析的类(除了NSString,NSNumber...等等)或者是个数组或字典,则继续递归解析。 并且会找到superClass的属性并解析,superClass如...
基于遗传算法辅助异构改进的动态多群粒子群优化算法(GA-HIDMSPSO)的LSTM分类预测研究(Matlab代码实现)内容概要:本文研究了一种基于遗传算法辅助异构改进的动态多群粒子群优化算法(GA-HIDMSPSO),并将其应用于LSTM神经网络的分类预测中,通过Matlab代码实现。该方法结合遗传算法的全局搜索能力与改进的多群粒子群算法的局部优化特性,提升LSTM模型在分类任务中的性能表现,尤其适用于复杂非线性系统的预测问题。文中详细阐述了算法的设计思路、优化机制及在LSTM参数优化中的具体应用,并提供了可复现的Matlab代码,属于SCI级别研究成果的复现与拓展。; 适合人群:具备一定机器学习和优化算法基础,熟悉Matlab编程,从事智能算法、时间序列预测或分类模型研究的研究生、科研人员及工程技术人员。; 使用场景及目标:①提升LSTM在分类任务中的准确性与收敛速度;②研究混合智能优化算法(如GA与PSO结合)在神经网络超参数优化中的应用;③实现高精度分类预测模型,适用于电力系统故障诊断、电池健康状态识别等领域; 阅读建议:建议读者结合Matlab代码逐步调试运行,理解GA-HIDMSPSO算法的实现细节,重点关注种群划分、异构策略设计及与LSTM的集成方式,同时可扩展至其他深度学习模型的参数优化任务中进行对比实验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值