是否有可能有返回类型为void构造函数?

问题描述 投票:-4回答:4

我想知道是否有可能有返回类型为void构造函数,如下面的例子。

例如

class A
{
    void A(){}  //where A is constructor and for which return type is void

    public static void main(string arg[]){
        A a = new A();
    }
}
java constructor
4个回答
6
投票

构造函数没有结果/返回类型。

如果添加一个结果/返回类型的“构造”你把它变成他的名字是一样的类名的方法。然后new将无法使用它,并在任何方法或this(...)电话super(...)将是一个语法错误。


对于你的榜样,你不会真正得到一个错误。这是因为Java将增加一个默认的无参数的构造为A ...因为你还没有真正定义的任何构造函数。在您的示例new将实际使用默认构造函数....

如果你改变了你的代码如下:

class A {
    void A() { System.err.println("hello"); }

    public static void main(string arg[]) {
        A a = new A();
    }
}

并编译和运行它,你应该看到,它不给你任何输出。取出void,你会看到输出。


所以这里A()的方法工作

这是>> <<一种方法。但它不是“工作”。正如我对你的实例版本显示......该方法不会被调用的。


0
投票

为什么你的代码编译你困惑。这是因为A()实际上不是一个构造函数,但一个方法(即不幸的是具有相同的名称作为类)。类A有一个用来通过main一个隐含的默认构造函数。该方法A()不被使用。

正如其他人所指出的那样,构造函数没有返回类型。



0
投票

希望这个例子会更容易理解。在这个例子中,你可以看到Main作为类,构造函数和方法,以及这些作品。请参阅输出了。 看到当你调用构造函数,当调用构造函数的方法发生了什么会发生什么。

程序:

//Class
public class Main
{
    //Constructor
    public Main(){ 
        System.out.println("Hello World 1");
    }

   //Method
    public void Main(){ 
        System.out.println("Hello World 2");
    }

   //Another method but static
    public static void main(String[] args) { //This should be small letter 'main'
        System.out.println("Hello World 3"); //Print this first

        Main constructor = new Main(); //Run constructor and print.
        constructor.Main(); //Run method (void Main()) and print.
    }
}

输出:

Hello World 3                                                                                                                         
Hello World 1                                                                                                                         
Hello World 2

注意:不遵循命名约定。

© www.soinside.com 2019 - 2024. All rights reserved.