ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 继承 课堂代码: ~~~java package com.dodoke.demo; public class Animal { protected String sex; protected int age; protected String color; protected String type; public void eatFood() { System.out.println(this.type + " is eating food"); } protected String sleep() { return this.type + " 正在睡觉"; } public Animal() { } public Animal(String type, int age) { this.type = type; this.age = age; } public Animal(String sex, int age, String color, String type) { super(); this.sex = sex; this.age = age; this.color = color; this.type = type; } } ~~~ ~~~Java package com.dodoke.demo; public class Dog extends Animal { private String bark; public String getBark() { return this.bark; } public void setBark(String bark) { this.bark = bark; } //继承语法 /** * [修饰符] class SubClass extends SuperClass { * 修饰符 class 子类名称 extends 父类名称 * } */ /** * 重写实际上针对父类的方法进行修改 * 通常会在重写的方法上加上注解 @Override * @param args */ @Override public String sleep() { return this.type + "正在躺着睡觉"; } /** * 重写的toString()方法 * 会在打印对象的时候,主动调用toString()方法,打印对象信息 */ @Override public String toString() { return "Dog [type = "+ this.type + ",age = "+ this.age +",color = "+ this.color +",sex = "+ this.sex +",bark = "+ this.bark +"]"; } /** * 使用super可以调用父类被覆盖的方法和父类的属性 */ public void getFatherMethodSleep() { System.out.println(super.sleep()); eatFood(); } /** * 调用父类构造器 * [修饰符] 类名() { * super();//在第一行调用父类构造器 * } */ public Dog() { super(); } public Dog(String type, int age) { super(); this.type = type; this.age = age; }; public Dog(String type, int age, String color) { super(type,age);//调用了父类的构造器,注意!!! //this(type,age);在同一构造器中,this()和super()只能出现一个 this.color = color; } public Dog(String sex, int age, String color, String type, String bark) { super(sex, age, color, type); this.bark = bark; } public static void main(String[] args) { Dog dog = new Dog(); dog.type = "狗 "; dog.age = 9; dog.color = "黑色"; dog.sex = "公"; dog.setBark("ww"); dog.eatFood(); System.out.println(dog.sleep()); dog.getFatherMethodSleep(); System.out.println(dog); Dog dog2 = new Dog("狗", 7, "白色"); System.out.println(dog2); } } ~~~