java“void”和“非空隙”构造函数 [英] java "void" and "non void" constructor

查看:111
本文介绍了java“void”和“非空隙”构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中写了这个简单的类,只是为了测试它的一些功能。

I wrote this simple class in java just for testing some of its features.

public class class1 {
    public static Integer value=0;
    public class1() {
       da();
    }
    public int da() {
        class1.value=class1.value+1;
        return 5;
    }
    public static void main(String[] args) {
       class1 h  = new class1();
       class1 h2 = new class1();
       System.out.println(class1.value);
    }
}

输出为:


2

2

但在此代码中:

public class class1 {
    public static Integer value=0;
    public void class1() {
        da();
    }
    public int da() {
        class1.value=class1.value+1;
        return 5;
    }
    public static void main(String[] args) {
        class1 h  = new class1();
        class1 h2 = new class1();
        System.out.println(class1.value);
    }
}

此代码的输出是:


0

0

在构造函数方法声明中使用 void ,类的静态字段不会再更改?

So why doesn't, when I use void in the constructor method declaration, the static field of the class doesn't change any more?

推荐答案

在Java中,构造函数不是一种方法。它只有类的名称和特定的可见性。如果它声明返回一些东西,那么它不是构造函数,即使它声明返回 void 。注意这里的区别:

In Java, the constructor is not a method. It only has the name of the class and a specific visibility. If it declares that returns something, then it is not a constructor, not even if it declares that returns a void. Note the difference here:

public class SomeClass {
    public SomeClass() {
        //constructor
    }
    public void SomeClass() {
        //a method, NOT a constructor
    }
}

此外,如果一个类没有定义一个构造函数,编译器会自动为你添加一个默认构造函数。

Also, if a class doesn't define a constructor, then the compiler will automatically add a default constructor for you.

这篇关于java“void”和“非空隙”构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆