问题描述
// final keyword usage
package workarea;
final class demo {
final int x=10;
////compile time exception here because ‘x’ is final type
System.out.println("hello modified x value is:"+ x);
final void m1()
{
int x=2;
System.out.println("hello modified x value is:"+x);
}
void m2()
{
System.out.println("hello modified m2 x value is:"+x);
}
public static void main(String abc[])
{
demo df=new demo();
System.out.println("welcome");
df.m1();
df.m2();
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at workarea.demo.main(demo.java:24)
解决方法
对于编译时异常,最好使用任何 Java IDE 的 -Eclipse、STS、Netbeans 和 IntelliJ 创建并运行程序以进行早期编译检测。
在上面的代码中,打印语句System.out.println("hello modified x value is:"+ x);
应该在块或方法中。
您在这里面临的问题是您试图在没有方法或实例初始化程序的情况下纯粹在类主体中编写语句。在 Java 中你不能这样做。 因此,请在方法或实例初始化程序中包含以下语句。
System.out.println("hello modified x value is:"+ x);
备选方案 1(使用方法):
public void sampleMethod(){
System.out.println("hello modified x value is:"+ x);
}
备选方案 2(使用实例初始值设定项):
{
System.out.println("hello modified x value is:"+ x);
}