布尔类型的实例变量的默认值是true还是false?

5
  1. 如果在类中创建一个实例变量,除非另有更改,否则默认值为true还是false?

  2. 将实例变量设置为true,然后将其更改为false并在整个类中使用该变量是好的做法吗?或者从概念上讲,这是您应该避免使用实例变量的东西?


3
可以通过查阅官方文档、教程甚至JLS来轻松回答这个问题。 - Rohit Jain
5个回答

9
如果在类中创建实例变量,那么默认值是true还是false,除非另有更改?
默认值为false。(JLS 4.12.5
将实例变量设为true,然后将其值更改为false并在整个类中使用该变量是一个好的做法吗?
我猜你的意思是,是否有良好的做法来定义布尔实例变量,以便您可以依赖于默认初始化。
答案是:不是好的做法。
  • It is good practice to define the instance variables so that they make sense to the reader of the code:

        // Good (probably)
        private boolean isValid = true;
    
        // Bad (probably)
        private boolean isNotValid;  // so that I can rely on default init
    

    (Now, it may make your code easier to understand if the variable is negated ... but the point is that you should decide based on what makes the code easy to understand ... not on based exploiting default initialization.)

  • It is bad practice to spend time worrying about performance issues at this level of granularity. The chances are that performance benefit of avoiding an explicit initialization is insignificant.


如果您想使用false作为默认值,isInvalid听起来不像isNotValid那么糟糕。 - zod
你误解了我的观点。问题不在于名称,而在于为何使用isInvalididNotValid而非isValid的动机。 - Stephen C
我觉得我明白了,而且我同意你的观点。我只是建议以我个人来说更可接受的方式写出你选择的特定示例(我的意思是,一个带有"not"这个词的布尔变量看起来很奇怪)。 - zod

4

JLS 4.12.5

  • 每个类变量、实例变量或数组元素在创建时都会被初始化为默认值(§15.9,§15.10):

    • 对于类型 byte,默认值为零,即值为(byte)0

    • 对于类型 short,默认值为零,即值为(short)0

    • 对于类型 int,默认值为零,即值为0

    • 对于类型 long,默认值为零,即值为0L

    • 对于类型 float,默认值为正零,即值为0.0f

    • 对于类型 double,默认值为正零,即值为0.0d

    • 对于类型 char,默认值为 null 字符,即值为 '\u0000'

    • 对于类型 boolean,默认值为 false

    • 对于所有引用类型 (§4.3),默认值为 null


3
如果在类中创建实例变量,除非另有更改,否则默认值是true还是false? 如果变量的类型为布尔型,则默认值为false,原始变量的默认值为0,对象变量/引用变量的默认值为null。
将实例变量设置为true,然后将其值更改为false并在整个类中使用该变量是否是良好的实践? 您可以这样做,这取决于您的要求。

1
when you crate a variable of boolean   
public class check  {
static boolean  b;
    public static void main(String args[]) {
            System.out.print("The Default Value of Boolean is="+b);
     }
   }

enter image description here


1
如果在类中创建实例变量,则默认值是true还是false,直到另有更改?
如果成员是原始类型,则为false。如果它是包装器,则为null。
将实例变量设置为true然后将其值更改为false并在整个类中使用该变量是好的做法吗?或者从概念上讲,在使用实例变量方面应该避免这种情况吗?
设置为true或false取决于您的类上下文。没有任何问题。
例如:您正在创建一个客户对象,并具有一个实例成员isActive。如果您的设计允许所有客户默认处于活动状态,则是正确的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接