是否可以使用void返回类型的构造函数?

时间:2015-03-22 03:12:53

标签: java constructor

我想知道是否可以使用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();
    }
}

4 个答案:

答案 0 :(得分:5)

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

如果将结果/返回类型添加到“构造函数”,则将其转换为名称与类名相同的方法。然后new将无法使用它,并且方法中的任何this(...)super(...)调用都将是语法错误。


对于您的示例,您实际上不会收到错误。这是因为Java将为A添加默认的no-args构造函数...因为您实际上没有定义任何构造函数。您的示例中的new实际上将使用默认构造函数....

如果您将代码更改为:

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

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

并编译并运行它,你应该看到它没有给你任何输出。移除void,您将看到输出。


  

所以这里A()作为方法

它>>是<<一个方法。但它并非“有效”。正如我的示例版本所示......根本没有调用该方法。

答案 1 :(得分:0)

您对代码编译的原因感到困惑。这是因为A()实际上不是构造函数,而是一个方法(不幸的是,它与该类具有相同的名称)。类A有一个隐式默认构造函数,由main使用。

}未使用方法A()

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

答案 2 :(得分:0)

答案 3 :(得分: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

注意::未遵循命名约定。