1.(1)构造方法名与类名相同.
(2)构造方法不返回任何值,也没有返回类型.
(3)每个类可以有零个或多个构造方法.
(4)构造方法在创建对象时自动执行,一般不能显式地直接调用.
2.在实例化时被调用,new的时候,new有参数的方法调有参构造方法,反之调无参构造方法
3.在类的继承中,子类的构造方法中默认会有super()语句存在,相当于执行父类的相应构造方法中的语句
如下面代码:
class Extends_Demo {
public static void main(String[] args) {
Cat c = new Cat(); //---------------(1)
System.out.println("-------------------");
Cat c1 = new Cat("花花",4); //----------------(2)
}
}
class Animal {
private String color;
private int foot;
public Animal(){
System.out.println("我是父类无参数构造器");
}
public Animal(String color,int foot){
System.out.println("我是父类有参数构造器");
this.color = color;
this.foot = foot;
}
}
class Cat extends Animal{
public Cat(){
super(); //---------------可以省略
System.out.println("我是子类无参数构造器");
}
public Cat(String color,int foot){
//super(color,foot); //---------------(3)
super(); //---------------可以省略
System.out.println("我是子类有参数构造器");
}
}
输出
对比后可以知道,super()代表执行父类无参数构造方法内容,super(color,foot)代表执行父类有参数构造方法。