我的带有 final 关键字的 java 代码有错误

问题描述

// 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)

错误信息针对提到 main 的代码行 帮我更正这段代码

解决方法

对于编译时异常,最好使用任何 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);

}