为什么您需要在非静态上下文 中使用final
变量?编译器是否自动将 static
分配给所有 final
变量?
编辑:我知道 static
和 final
之间的区别,我想问的是是否有任何情况下您需要 final int x
而不是 static final int x
。当您无法修改 x
时,为什么在每个实例中都需要它的副本?
最佳答案
关键字 final
用于在构造时允许分配值仅一次。
public class Person {
public final String name;
public Person(String name) {
this.name = name;
}
}
Person p = new Person("a");
p.name = "newName"; // COMPILE ERROR name is marked as "final" thus can not be changed.
when you would need final int x instead of static final int x?
考虑这些类:
public class OriginConstants {
// static final fields allows to access constants via class accessor i. e. OriginConstants.x (no need to create instance)
public static final int x = 0;
public static final int y = 0;
}
public class ImmutablePoint {
public final int x;
public final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public class MutablePoint {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
使用示例
// create immutable point shifted from coordinate system origin by 5
ImmutablePoint ip = new ImmutablePoint(OriginConstants.x + 5, OriginConstants.y + 5);
// updating point coordinate by 10
ip.x += 10; // COMPILE ERROR
ip.y += 10; // COMPILE ERROR
// we cannot modify final fields, but we can create new instance with shifted coordinates
ImmutablePoint shiftedIp = new ImmutablePoint(ip.x + 10, ip.y + 10);
// create mutable point shifted from coordinate system origin by 5
MutablePoint mp = new MutablePoint(OriginConstants.x + 5, OriginConstants.y + 5);
// updating point coordinate by 10
ip.x += 10; // OK
ip.y += 10; // OK
我会为一些不能及时改变的坐标使用不可变点。假设,我们有 height = 100,width = 100 的 Canvas 。我们可以按如下方式创建辅助常量点:
public class Canvas {
public static final int HEIGHT = 100;
public static final int WIDTH = 100;
// anchor points
public static final ImmutablePoint topLeft = new ImmutablePoint(0,0);
public static final ImmutablePoint topRight = new ImmutablePoint(Canvas.WIDTH, 0);
public static final ImmutablePoint bottomLeft = new ImmutablePoint(0, Canvas.HEIGHT);
public static final ImmutablePoint bottomRight = new ImmutablePoint(Canvas.WIDTH, Canavas.HEIGHT);
}
这样我们就可以确定 topLeft
始终为 0,0 并且不会因错误而更改。
关于java - 为什么不是所有最终变量默认都是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44803713/