constructor have include a void return type?

for example

class A {

void A() //where A is constructor and which return type is void,it is valid

{

}

public static void main(string arg[])

A a = new A();

}


A constructor does not have a result / return type.

If you add a result / return type to a "constructor" you turn it into a method whose name is the same as the class name. Then new won't be able to use it, and any this(...) or super(...) call in the method will be a syntax error.


For your example, you won't actually get an error. That is because Java will add a default no-args constructor for A ... because you haven't actually defined any constructors. The new in your example will actually be using the default constructor ....

If you changed your code to this:

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

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

and compiled and ran it, you should see that it DOES NOT give you any output. Remove the void and you will see output.


so here A() work as a method

It >>is<< a method. But it is not "working". As my version of your example shows ... the method is not being called at all.


You are confused why your code compiles. It's because A() is not actually a constructor but a method (that unfortunately has the same name as the class). The class A has an implicit default constructor which is used by main . The method A() is not used.

As others have pointed out, constructors do not have a return type.

链接地址: http://www.djcxy.com/p/49634.html

上一篇: setInterval替代

下一篇: 构造函数有一个void返回类型?