gpt4 book ai didi

java - 是 Netbeans Bug 还是为了方便?

转载 作者:行者123 更新时间:2023-11-30 08:46:56 25 4
gpt4 key购买 nike

我正在使用 NetBeans 并面临以下通知。

1) 当我声明和初始化 private final int a=3; 时,Netbeans 通知我将 Initialize 移至 Constructor 为什么?

2) 当我声明并初始化 private int a=3; 时,Netbeans 通知我 field can be final 直到我在 Constructor 中初始化它。即使在 Instance Members Block 中初始化也会导致同样的问题。

有什么帮助吗?为什么我会收到这些通知?

1)代码

public class Testing 
{
private final int a=3;
static{
System.out.println("Static Block");
}
Testing(){
System.out.println("Constructor");
}
public static void main( String args[])
{
Testing obj=new Testing();
}
}

2)代码

public class Testing 
{
private int a;
static{
System.out.println("Static Block");
}
{
this.a=0;
System.out.println("Instance Member Initializer");
}
Testing(){
this.a = 3; // when I remove this I got 1) Problem
System.out.println("Constructor");
}
public static void main( String args[])
{
Testing obj=new Testing();
}
}

最佳答案

private final int n=3;

因为变量不是静态的,即在类级别。

NetBeans 要求您将其放入构造函数中。这不是错误,只是指南。

Oracle java doc 中所述

public class BedAndBreakfast {

// initialize to 10
public static int capacity = 10;

// initialize to false
private boolean full = false;
}

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

关于java - 是 Netbeans Bug 还是为了方便?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32698236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com