如果您声明一个变量为 static 和 final,则需要在声明时或在静态块中初始化它。如果您尝试在构造函数中初始化它,编译器会假设您尝试重新分配值,并生成编译时错误 - 示例 实时演示 class Data { static final int num; Data(int i) { num = i; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } } 编译时错误 ConstantsExample.java:4: error: cannot assign a value to ... 阅读更多
一个未初始化的 final 变量被称为空白 final 变量。通常,我们在构造函数中初始化实例变量。如果我们遗漏了它们,构造函数将用默认值初始化它们。但是,final 空白变量不会用默认值初始化。因此,如果您尝试在没有在构造函数中初始化的情况下使用空白 final 变量,则会生成编译时错误。示例 实时演示 public class Student { public final String name; public void display() { System.out.println("Name of the Student: "+this.name); } public static void main(String args[]) { ... 阅读更多
每当您将方法设为 final 时,您就无法覆盖它。即,您不能从子类为超类的 final 方法提供实现。即,使方法成为 final 的目的是防止从外部(子类)修改方法。在继承中,每当您扩展一个类时。子类继承超类所有成员,构造函数除外。换句话说,构造函数不能在 Java 中继承,因此您不能覆盖构造函数。因此,在构造函数前写 final 没有意义。因此,java 不允许在构造函数前使用 final 关键字。如果您尝试使构造函数成为 final,则会发生编译时错误…… 阅读更多
当您尝试使用子类对象持有超类的引用变量时,使用此对象,您只能访问超类的成员,如果您尝试使用此引用访问派生类的成员,则会收到编译时错误。示例 实时演示 interface Sample { void demoMethod1(); } public class InterfaceExample implements Sample { public void display() { System.out.println("This ia a method of the sub class"); } public void demoMethod1() { System.out.println("This is demo method-1"); } public static void main(String args[]) ... 阅读更多