day14
第一題:(問答題)
1. 什么叫做多態,條件是什么?
(1)同一個方法在不同的對象上有不同的表現形式
(2)條件: 要有繼承關系
子類要重寫父類方法
要通過父類的引用指向子類的對象
2. 使用多態特性,帶來了什么樣的好處?
方法中,使用父類型作為參數,可以接收所有的子類對象
3. 使用多態特性,注意什么樣的弊端?
不能直接訪問子類特有的成員
4. 關于多態的弊端我們如何解決?
自動類型轉換,強制類型轉換
5. 在A包中我要同時使用B包下的Student和C包下的Student類,該如何使用?
import導包或者全限定名
6. final修飾類,修飾方法,修飾變量的特點?
(1)修飾類:最終類,不能被繼承
(2)修飾方法:最終方法,不能被重寫
(3)修飾變量:是常量,不能被修改
第二題:代碼練習
完成課堂解決飼養員飼養動物的案例即可
public class Animal {
private int age;
private String color;
public Animal() {
}
public Animal(int age, String color) {
this.age = age;
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void eat(String something) {
System.out.println("吃" + something);
}
}
public class Cat extends Animal{
public Cat() {
}
public Cat(int age, String color) {
super(age, color);
}
public void catchMouse() {
System.out.println("小貓抓老鼠");
}
public void eat(String something) {
System.out.println(getAge()+"歲的"+getColor()+"顏色的貓瞇著眼睛側著頭吃"+ something);
}
}
public class Dog extends Animal{
public Dog() {
}
public Dog(int age, String color) {
super(age, color);
}
public void lookHome() {
System.out.println("汪汪汪");
}
public void eat(String something) {
System.out.println(getAge()+"歲的"+getColor()+"顏色的狗兩只前腿死死的抱住"+something+"猛吃");
}
}
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void keepPet(Animal a, String something){
if(a instanceof Dog){
System.out.println("年齡為"+age+"歲的"+name+"養了一只"+a.getColor()+"顏色的"+a.getAge()+"歲的狗");
}else if(a instanceof Cat){
System.out.println("年齡為"+age+"歲的"+name+"養了一只"+a.getColor()+"顏色的"+a.getAge()+"歲的貓");
}else{
System.out.println("沒有這個動物");
}
}
}
public class Text {
public static void main(String[] args){
//創建人對象
Person person = new Person("老王", 30);
Person person1 = new Person("老李", 25);
//創建狗對象
Dog dog = new Dog(2, "黑");
//創建貓對象
Cat cat = new Cat(3, "灰");
//調用方法
person.keepPet(dog, "骨頭");
dog.lookHome();
dog.eat("骨頭");
person1.keepPet(cat, "魚");
cat.eat("魚");
cat.catchMouse();
}
}
浙公網安備 33010602011771號