java super关键字简述
- super关键字访问父类属性,访问权限必须是允许的
- super关键字访问父类属性,访问权限必须是允许的
- 当创建子类对象时,默认调用父类的无参构造方法,除非显式调用父类的有参构造方法,也就是说
**子类创建对象时,父类构造方法,必须调用一个**
,要么调用一个父类的无参构造方法,要么调用一个父类的有参构造方法
注意: 通过super关键字可以访问父类的构造方法,要求必须写在子类构造方法的第一句
package com.qfedu.Test7;
/*** 宠物父类* 姓名* 爱心值* 健康值* @author **/
public class Pet {public String name;public int health;public int love;public void setName(String name) {this.name = name;}public String getName() {return name;}public void setHealth(int health) {if (health>=0&&health<=100) {this.health = health;}else {System.out.println("健康值输入错误,默认60");this.health = 60;}}public int getHealth() {return health;}public void setLove(int love) {this.love = love;}public int getLove() {return love;}public void print() {System.out.println("宠物名字为:"+name);System.out.println("宠物健康值为:"+health);System.out.println("宠物爱心值为:"+love);}public Pet(String name,int health,int love) {this.name = name;this.health = health;this.love = love;}public Pet() {System.out.println("父类无参构造");}
}
package com.qfedu.Test7;
/*** 宠物的子类 Dog类* @author **/
public class Dog extends Pet{private String strain;public String getStrain() {return strain;}public void setStrain(String strain) {this.strain = strain;}public Dog(String name ,int health ,int love,String strain) {super(name,health,love);//调用有参构造必须在第一行System.out.println("调用了有参构造");this.strain = strain;}public void printDog() {super.print();System.out.println("狗的品种是: "+strain);}public Dog() {}}
package com.qfedu.Test7;
/*** 宠物的子类 企鹅类* @author **/
public class Penguin extends Pet{private String sex;public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Penguin(String name ,int health ,int love,String sex) {this.sex = sex;super.health = health;super.love = love;super.name = name;}public void printPenguin() {super.print();System.out.println("企鹅性别是:"+sex);}public Penguin() {}}
package com.qfedu.Test7;/*** 测试类* 子类对象创建 必须调用一个父类构造方法* @author **/
public class Test {public static void main(String[] args) {//调用了有参构造Dog dog = new Dog("张三",100,100,"拉布拉多");dog.printDog();System.out.println("==================");//默认调用一个无参构造方法Penguin penguin1 = new Penguin("李四",20,30,"雌性");penguin1.printPenguin();}
}