//需求:实现多态
//功能演化,先要求,能继承父类,实现,功能。
//猫吃鱼,狗吃骨头,猪吃饲料。
//猫狗猪都有自己的特有属性,他们都属于动物。
//功能演化,先要求,能继承父类,实现,功能。
//猫吃鱼,狗吃骨头,猪吃饲料。
//猫狗猪都有自己的特有属性,他们都属于动物。
//第124行的 问题。没有解决。
abstract class Animal
{
public abstract void eat();
}
class Cat extends Animal
{
public void eat() //之前这里 没有写public 可是父类有public ,运行提示:子类eat无法覆盖父类的eat。所以加上public。
{
System.out.println("鱼");
}
public void catchMouse()
{
System.out.println("抓老鼠");
}
}
class Dog extends Animal
{
public void eat()
{
System.out.println("骨头");
}
public void seeHouse()
{
System.out.println("看家");
}
}
class Pig extends Animal
{
public void eat()
{
System.out.println("饲料");
}
public void sleep()
{
System.out.println("睡觉");
}
}
class DuoTaiDemo
{
public static void main(String[] args)
{
//Animal c = new Cat(); //在Animal替换Cat的时候,要注意的前提是,Cat继承了Animal。
//c.eat();
//Animal d = new Dog();
//d.eat();
//Animal p = new Pig();
//p.eat();
function(new Dog());
function( new Cat());
function(new Pig());
/*
Animal a = new Cat();
Animal a = new Cat();
a.eat();
Cat c = (Cat)a;
c.catchMouse();
*/
}
*/
}
/*
public static void function(Cat c)
{
c.eat();
}
public static void function(Dog d)
{
d.eat();
}
public static void function(Pig p)
{
p.eat();
}
*/
public static void function(Animal a ) //实现,功能简化。多态,实现功能扩展性。
{
a.eat();
if(a instanceof Cat) // instanceof 引用类型的数据判断使用的.一般,只有很少几个判断的时候才用。
{
Cat c = (Cat)a;
public static void function(Cat c)
{
c.eat();
}
public static void function(Dog d)
{
d.eat();
}
public static void function(Pig p)
{
p.eat();
}
*/
public static void function(Animal a ) //实现,功能简化。多态,实现功能扩展性。
{
a.eat();
if(a instanceof Cat) // instanceof 引用类型的数据判断使用的.一般,只有很少几个判断的时候才用。
{
Cat c = (Cat)a;
c.catchMouse();
}
else if(a instanceof Dog)
{
Dog c = (Dog)a;
}
else if(a instanceof Dog)
{
Dog c = (Dog)a;
c.seeHouse();
}
else
{
Pig c= (Pig)a;
c.sleep();
System.out.println("剩下就是猪的事了。");
}
}
}
else
{
Pig c= (Pig)a;
c.sleep();
System.out.println("剩下就是猪的事了。");
}
}
}
/*
父类 x = new 子类(); //类型提升,向上转型。
/*
父类 x = new 子类(); //类型提升,向上转型。
x.功能(); // 如果想要强制将父类的引用。转换成子类类型,向下转型. (这个功能,如果父类没有的话,能过实现吗? )
子类 y = (子类)x; // 不能将父类的对象转成子类类型。我们能转换的是父类应用指向了自己的子类对象时。该应用可以被提升,也可以被强制转换。
y.功能(); //子类的功能。
//这里面转来转去,都是子类在变化,实现的功能都是子类的。(多态自始至终都是子类对象在做变化。)
*/