java中能在main方法中调用构造方法吗

public class AnyThing {

public AnyThing(){
this(5);
System.out.println("无参数构造方法");
}

public AnyThing(String name){
System.out.println(name);
}

public AnyThing(int age){
System.out.println("年龄是"+age);
}

public static void main(String[] args){
AnyThing a = new AnyThing();
a.AnyThing("1111111");
}
}
提示:The method AnyThing(String) is undefined for the type AnyThing。
但是 AnyThing(String name) 方法已经定义了啊,main()方法中不能调用构造函数吗?

构造方法都是不能直接被调用的,它是在实例化的时候被调用的。如果你想用到有参构造方法,你可以这样实例化AnyThing a = new AnyThing("1111111");追问

哦,我明白了,我的程序里面的a是通过无参数的构造方法实例出来的对象,构造方法只能通过new来进行实例化。构造方法是不能通过“.”来调用的,其他的成员方法是可以通过“.”来调用的,是吧?

追答

对,公有的方法可以,私有的只能在类中自己调用

温馨提示:答案为网友推荐,仅供参考
相似回答