当子类继承父类的时候,若父类没有定义带参的构造方法,则子类可以继承父类的默认构造方法
当父类中定义了带参的构造方法,子类必须显式的调用父类的构造方法
若此时,子类还想调用父类的默认构造方法,必须在父类中明确声明默认的构造方法
1 package com.gaohui; 2 3 public class Test { 4 public static void main(String [] args){ 5 Man man = new Man(24,"Tom"); 6 man.eat(); 7 man.eat("Tom"); 8 man.Exercise(); 9 Woman woman = new Woman(); 10 11 } 12 13 } 14 15 class People{ 16 private int age; 17 private String name; 18 private String sex; 19 20 public People(){ 21 //如果父类没有声明默认的构造方法,子类继承时必须显式调用父类定义的构造方法 22 } 23 24 public People(int age, String name){ 25 System.out.println("构造方法一执行了!"); 26 } 27 28 public void eat(){ 29 System.out.println("People need to eat!"); 30 } 31 32 public void eat(String name){ 33 System.out.println(name+" needs to eat!"); 34 } 35 36 37 } 38 39 class Man extends People{ 40 public Man (int age, String name){//由于父类的构造方法是有参的,必须显式调用父类的方法 41 super(age,name); 42 } 43 44 public void Exercise(){ 45 System.out.println("I love doing exercise!"); 46 } 47 } 48 49 50 class Woman extends People{ 51 52 }
时间: 2024-10-21 00:39:41