【发布时间】:2015-10-05 10:06:50
【问题描述】:
public class FinalClassVariable {
public static void main(String[] args) {
ClassVariable classVariable = new ClassVariable();
System.out.println("Value of PI accessed thorugh class itself = "+ClassVariable.PI);
//System.out.println(ClassVariable.E);
System.out.println("Value of PI accessed thorugh object = "+classVariable.PI);
System.out.println("The value of constant E = " + classVariable.E);
}
}
class ClassVariable {
public static final double PI = 3.14;
public final double E = 2.7182818284590452353602874713527;
}
变量 'PI' 和 'E' 之间的主要区别我们可以通过 类名和对象和'E'都只能通过对象访问
而且这两个都是常数,我们不会改变它们的值。
我已经完成了马德里卡洛斯三世大学的 Java 课程 大学,还观看了 Mehran Sahami 的斯坦福大学视频
这两个人都建议在 final 中使用关键字 static。
我的问题是,如果我们可以通过声明 final 来创建常量
那为什么我们还要声明它static? static 也妥协了 OOP 的概念。
这两个声明之间有什么细微差别吗?哪一种最适合我们的应用程序?
【问题讨论】:
-
不,
static不会自动破坏 OOP。在 OOP 中避免使用staticvariables 通常有充分的理由,但它们不适用于常量。这是一个例子,说明人们如何采用有用的原则并将其过度简化,以至于它们可能成为破坏性的神话。
标签: java