Java继承时构造函数的调用

/**
 *  父类Parent 
 *
 */
public class Parent {

        public String strName;
public int intAge;

/**
 * 无参构造函数
 *  
 */
public Parent() {

System.err.println("Parent无参构造函数");
}


/**
 * 有参构造函数
 * @param strName
 * @param intAge
 */
public Parent(String strName , int intAge) {

strName = this.strName;
intAge = this.intAge;
System.err.println("Paren有参构造函数");
}
}

/**
 *  子类Parent 
 *
 */
public class Child extends Parent {

public String strName;
public int intAge;

/**
 * 无参构造函数 
 */
public Child(){

System.err.println("Child无参构造函数");
};

public Child(String strName , int intAge) {

strName = this.strName;
intAge = this.intAge;

System.err.println("Child有参构造函数");
}
}

/**
 * 
 *  测试类别
 */
public class ExtendTest {

/**
 * @param args
 */
public static void main(String[] args) {

Parent parent = new Parent();       (1)
Child child = new Child();          (2)
Parent parentTest = new Child();    (3)
}

}

(1)结果
============
Parent无参构造函数
============

(2)结果
============
PaParent无参构造函数
Child无参构造函数
============

(3)结果
============
PaParent无参构造函数
Child无参构造函数
============

总结
1).调用子类别的构造方法,会先行调用父类别的构造方法.
2).如果有自定义的构造方法,编译器就不会提供无参构造方法.否则,编译器会提供无参构造方法.
3).如果Parent中没有重写无参构造方法,编译会通过.因为子类在寻找父类的构造方法的时候,发现只有带参数的构造方法.而没有无参构造方法.
4).同样如果想将Parent中无参构造方法的访问级别设为private,同样会有3)中的问题.
5).子类想调用父类的构造方法,用super(); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值