abstract class Animal
{
abstract void eat();
}
class Dog extends Animal
{
public void eat() {
System.out.println("啃骨头");
}
public void play() {
System.out.println("玩球球");
}
}
class Cat extends Animal
{
public void eat() {
System.out.println("吃鱼");
}
public void CatchMouse() {
System.out.println("抓老鼠");
}
}
public class DuoTaiDemo {
public static void main(String[] args) {
// Cat c = new Cat();
// Dog d = new Dog();
// c.eat();
// d.eat();
// method(new Cat());
// method(new Dog());
// Animal a = new Cat();//自动类型提升,猫对象提升为动物类型。
// a.eat();//但是会造成猫对象的特有功能无法被访问。
// //其作用就是限制对特有功能的访问。
// //专业上讲:向上转型。
//
// //如果还想使用猫的特有功能。
// //可以将对象进行向下转型。
// Cat c = (Cat)a;//向下转型的目的就是为了调用特有方法。
// c.CatchMouse();
method(new Cat());
}
public static void method(Animal a) {
a.eat();
//如果传进来一个animal 我想对animal的子类调用其特有方法。
//之前所说是通过向下转型。即:
Cat c = (Cat)a;
c.CatchMouse();
//然而animal的子类有很多,传进来的不一定是cat
//因此,我们需要对其进行类型判断。引入关键字:instanceof
if(a instanceof Dog)//通常在对象向下转型之前进行益于健壮性的判断。
{
Dog d = (Dog)a;
d.play();
}
}
}