构造方法有返回类型----该类的类型
如:A a=new A();
----------------------------
构造方法对返回类型没有选择权,也就是说不加任何返回修饰符,以示与其他的方法的区别
--void 表示我可以控制它返回类型,就是不让它返回嘛,显然有选择权了
这样编译器才发现,喔~~,原来这个就是构造方法,然后被编译器加上默认的类返回类型
-----------------------------------------
如果你硬要加上返回类型的话,就不是构造方法啦
public class A {
public int A() {
System.out.println("OK");
return 0;
}
public static void main(String[] args) {
new A();
}
}
------------------
上面的程序当然不会打印OK啦
因为编译器把public int A(){}当成成员方法,而不是构造方法
A constructor is used in the creation of an object that is an instance of a class:
In all other respects, the constructor declaration looks just like a method
declaration that has no result type.
Constructor declarations are not members.
看下面的例子:
public class TestConstructor {
public static void main(String[] args) {
A a = new A();
System.out.println(a.x);
a.A();//一般方法调用
System.out.println(a.x);
}