?? girlshavapets.java
字號:
package ch7.section7_3;
public class GirlsHavaPets {
public static void main(String[] args) {
Cat cat1 = new Cat("lingling", "白");
Dog dog1 = new Dog("jiajia", "黑");
Dog dog2 = new Dog("yuanyuan", "灰");
Girl g1 = new Girl("girl 1", cat1);
Girl g2 = new Girl("girl 2", dog1);
Girl g3 = new Girl("girl 3", dog2);
dog2.setState(0); //設定2號狗的狀態為睡著狀態
g1.petRun();
g2.petRun();
g3.petRun();
}
}
class Girl {
private String name;
private Animal pet; //girl養了一個寵物
Girl(String name, Animal pet) {
this.name = name;
this.pet = pet;
}
void petRun() {
System.out.print(name+"'s pet:");
pet.run(); //父類引用指向子類對象
}
}
class Cat extends Animal {
Cat(String name, String color) {
super(name, color);
}
//重寫了父類的run()方法
void run() {
if(this.state == 1) {
System.out.println(this.name + "在跑!");
} else {
System.out.println(this.name + "已睡著!");
}
}
}
class Dog extends Animal {
Dog(String name, String color) {
super(name, color);
}
//重寫了父類的run()方法
void run() {
if(this.state == 1) {
System.out.println(this.name + "在跑!");
} else {
System.out.println(this.name + "已睡著!");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -