java构造方法实例源码总结。
第一个public类
public class ConstructorDemo {
public static void main(String[] args) {
//new ConstructorA();//如果写了有参数的构造方法,就必须使用。此处会报编译错误。
//new ConstructorA();//同理,不管有没有写public
new ConstructorC();//但是,如果你写了无参的构造方法,就可以。
new ConstructorA(“namea”);
new ConstructorB(“nameb”);
}
}
class ConstructorA{
public ConstructorA(String name){
}
}
class ConstructorC{
public ConstructorC(String name){
}
public ConstructorC(){
}
}
class ConstructorD extends ConstructorC{
public ConstructorD(){
//this(1);//不能互调
this(“”);//可以调其它的
}
public ConstructorD(String name){
super();
//super(“”);父类构造方法只能调用一次,只能写在第一行!
}
public ConstructorD(int age){
this();
//this(“”);本类构造方法也只能调用一次,只能写在第一行!
}
}
第二个个public类
public class ConstructorB {
public ConstructorB(String name){
}
}
总结:
构造方法可以不写,不写就默认写了个无参的构造方法,所以也只能调用到这个无参构造方法。
但如果写了构造方法,不管写的哪一个,调用的时候,只能从已写的构造方法中调用,没写的会被认为不存在。
this()调本类的构造方法,spuer()调父类的构造方法。
只能写在第一行!
不能互调。