JAVA子类重写父类的构造函数时时,在对子类对象实例化的时候会自动调用父类的构造函数(会在子类的构造函数中省略super()的方法)
如
class Father {
private int age;
private String name ;
public Father(){
System.out.println("父类构造方法");
}
}
class Son extends Father{
public Son(){
System.out.println("子类构造方法");
}
}
public class haha8 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Son son=new Son();
// System.out.println(son);
}
}
会输出:
父类构造方法
子类构造方法
在子类中重写父类的普通方法则不会主动调用父类的方法,如
package haha7;
class A{
public void tell(){
System.out.println("我是tell方法");
}
}
class B extends A{
public void tell(){
//super.tell();
System.out.println("我重写了tell方法");
}
}
public class haha7 {
public static void main (String [] args){
B b = new B();
b.tell();
}
}
会输出:
我重写了父tell方法
如果想执行父类的方法,则需通过super.tell(); 调用