多态的习题
/*
多态的练习:
猫狗案例
*/
class Animal2{
public void eat(){
System.out.println("吃饭");
}
}
class Dog2 extends Animal2{
@Override
public void eat() {
System.out.println("狗吃肉");
}
public void lookDoor(){
System.out.println("狗看门");
}
}
class Cat2 extends Animal2{
@Override
public void eat() {
System.out.println("猫吃鱼");
}
public void catchMouse(){
System.out.println("猫抓老鼠");
}
}
public class PolymorphicTest1 {
public static void main(String[] args) {
Animal2 a = new Dog2();
a.eat();
//多态不能使用子类的特有方法
// a.lookDoor();
System.out.println("-----------------");
//通过向下转型使用子类的特有方法
Dog2 d = (Dog2)a;
d.eat();
d.lookDoor();
System.out.println("------------------");
//可以直接赋值,因为a是Animal2类型的
//相当于Animal2 a = new Cat2();
//将new Cat2()地址值赋给a
a = new Cat2();
a.eat();
//多态不能使用子类的特有方法
// a.catchMouse();
System.out.println("------------------");
//通过向下转型使用子类的特有方法
Cat2 c = (Cat2)a;
c.eat();
c.catchMouse();
//动物和猫之间转换与狗没关系
// c.lookDoor();
System.out.println("------------------");
//写反了
// Dog2 dog2 = new Animal2();
//这个很显然不行
// Dog2 dog2 = new Cat2();
//狗和猫没有继承关系,类型转换异常
// Dog2 dog2 = (Dog2)a;
// dog2.eat();
}
}
/*
不同地方饮食文化不同的案例
Person
eat()
SouthPerson
eat()
NorthPerson
eat()
*/
class Person{
public void eat(){
System.out.println("吃饭");
}
}
class SouthPerson extends Person{
@Override
public void eat() {
System.out.println("吃米饭");
}
public void work(){
System.out.println("创业");
}
}
class NorthPerson extends Person{
@Override
public void eat() {
System.out.println("吃面食");
}
public void bath(){
System.out.println("搓澡");
}
}
public class PolymorphicTest2 {
public static void main(String[] args) {
Person p = new SouthPerson();
p.eat();
//多态不能访问子类中特有的方法
// p.work();
System.out.println("-------------------");
//向下转型访问子类中特有的方法
SouthPerson sp = (SouthPerson)p;
sp.eat();
sp.work();
System.out.println("-------------------");
//将new NorthPerson()地址值赋给p
p = new NorthPerson();
p.eat();
//多态不能访问子类中特有的方法
// p.bath();
System.out.println("--------------------");
//向下转型访问子类中特有的方法
NorthPerson np = (NorthPerson)p;
np.eat();
np.bath();
}
}
/*
看程序,写结果
*/
class Fu {
public void show() {
System.out.println("fu show");
}
}
class Zi extends Fu {
public void show() {
System.out.println("zi show");
}
public void method() {
System.out.println("zi method");
}
}
public class PolymorphicTest3 {
public static void main(String[] args) {
Fu f = new Zi();
//多态访问成员变量的特点
// f.method();
//向下转型
Zi z = (Zi)f;
z.method();
}
}
/*
看程序写结果
*/
class A1 {
public void show() {
show2();
}
public void show2() {
System.out.println("我");
}
}
class B1 extends A1 {
//这里隐含了继承过来的show方法,只不过我们没有重写
// public void show() {
// show2();
// }
public void show2() {
System.out.println("爱");
}
}
class C1 extends B1 {
public void show() {
super.show();
}
public void show2() {
System.out.println("你");
}
}
public class PolymorphicTest4 {
public static void main(String[] args) {
A1 a = new B1();
//调用B1的show方法B1里没有,但是继承了A1的show方法
a.show(); // B1 爱
//多态创建对象
B1 b = new C1();
//多态访问成员方法的特点
b.show(); //C1 你
}
}