引用类型变量的转型
2016-07-06 16:27
281 查看
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
*/
相关文章推荐
- 生命不停应当大步的向前
- 数据库设计三范式
- 关于exec命令函数
- libubox组件(3)——uloop
- EventBus关于在FragmentActivity和Fragment中传值把我整安逸
- startActivityForResult和setResult
- APP上线加急审核-个人经历
- org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML doc
- mpandroidchart回退教程
- 闭包 -> map / floatMap / filter / reduce 浅析
- 今天看到一个签名,有点意思
- Android如何调用第三方SO库
- usb驱动的基本结构和函数简介【转】
- A计划
- openstack----03_ 安装Keystone
- 面向对象之接口
- Git 常用命令大全
- PTA 水...
- 机器学习 计算机视觉顶级会议文章免费下载
- linux查看硬盘使用情况-iotop