class Animal
{
private String name;
Animal(String name)
{
this.name = name;
}
}
class Dog extends Animal
{
private String furColor;
Dog(String name,String furColor)
{
super(name);
this.furColor = furColor;
}
void laugh(Animal a)
{
if(a instanceof Dog)
{
Dog d = (Dog)a;
System.out.println("furColor is "+d.furColor+"'s dog " +"laughs");
}
}
}
class Cat extends Animal
{
private String eyeColor;
Cat(String name,String eyeColor)
{
super(name);
this.eyeColor = eyeColor;
}
void laugh(Animal a)
{
if(a instanceof Cat)
{
Cat c = (Cat)a;
System.out.println("eyeColor is "+c.eyeColor+"'s cat " +"laughs");
}
}
}
public class TestCasting
{
public static void main(String[] args)
{
Animal a = new Animal("Animal");
Dog d = new Dog("Dog","yellow");
Cat c = new Cat("Cat","blue");
//a.laugh();
Dog d1 = new Dog("Dog1","black");
d.laugh(d1);
c.laugh(c);
}
}
/*
总结:
1.对象转型可以提高程序的扩展性
2.父类引用可以指向子类对象,但是父类只能访问子类从父类继承来的东西
而不能访问子类所特有的
3.转型(casting)
upcasting和downcasting
*/
{
private String name;
Animal(String name)
{
this.name = name;
}
}
class Dog extends Animal
{
private String furColor;
Dog(String name,String furColor)
{
super(name);
this.furColor = furColor;
}
void laugh(Animal a)
{
if(a instanceof Dog)
{
Dog d = (Dog)a;
System.out.println("furColor is "+d.furColor+"'s dog " +"laughs");
}
}
}
class Cat extends Animal
{
private String eyeColor;
Cat(String name,String eyeColor)
{
super(name);
this.eyeColor = eyeColor;
}
void laugh(Animal a)
{
if(a instanceof Cat)
{
Cat c = (Cat)a;
System.out.println("eyeColor is "+c.eyeColor+"'s cat " +"laughs");
}
}
}
public class TestCasting
{
public static void main(String[] args)
{
Animal a = new Animal("Animal");
Dog d = new Dog("Dog","yellow");
Cat c = new Cat("Cat","blue");
//a.laugh();
Dog d1 = new Dog("Dog1","black");
d.laugh(d1);
c.laugh(c);
}
}
/*
总结:
1.对象转型可以提高程序的扩展性
2.父类引用可以指向子类对象,但是父类只能访问子类从父类继承来的东西
而不能访问子类所特有的
3.转型(casting)
upcasting和downcasting
*/