11.子类实例化过程

  • 生成子类的过程
  • 子类继承了父类的成员变量,但却无法继承父类的构造函数
    • 当生成子类对象的时候,一定会调用父类的构造函数
    • 如果子类当中没有调用构造函数,编译器会自动添加super(),用于调用父类当中的无参数构造函数
 
 
  • 使用super调用父类构造函数的方法
    • 在子类要调用父类函数的话,super()一定要是构造函数的第一条语句
 
  1. classPerson{
  2. String name;
  3. int age;
  4. int grade;
  5. Person(){
  6. System.out.println("Person的无参数构造函数");
  7. }
  8. Person(String name ,int age){
  9. this.name = name;
  10. this.age = age;
  11. System.out.println("Person的有参数构造函数");
  12. }
  13. void eat(){
  14. System.out.println("吃饭");
  15. }
  16. }
 
  1. classStudent extends Person{
  2. //在子类的构造函数当中,必须调用父类的构造函数
  3. Student(){
  4. super();
  5. System.out.println("student的无参数构造函数");
  6. }
  7. Student(String name,int age,int grade){
  8. //this.name = name;
  9. //this.age = age;
  10. super(name,age);
  11. this.grade = grade;
  12. }
  13. }
 
  1. classTest{
  2. publicstaticvoid main(String args []){
  3. Student student =newStudent("zhagnsan",18,3);
  4. System.out.println(student.name);
  5. System.out.println(student.age);
  6. System.out.println(student.grade);
  7. }
  8. }
 
结果:
D:\work\src>javac *.java
D:\work\src>java Test
Person的有参数构造函数
zhagnsan
18
3





转载于:https://www.cnblogs.com/arroneve/p/5815434.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值