JAVA笔记8-对象转型casting
2024-10-07 02:42:54
1、规则
(1)基类(父类)的引用类型变量可以指向其子类对象;(向上转型)
(2)基类的引用不可以访问其子类对象新增加的成员(属性和方法);
(3)可以使用“引用变量 instanceof 类名”来判断该引用变量所指向的对象是否属于该类(或该类的子类);
(4)子类对象可以当做基类对象来使用,即基类引用指向子类对象,是向上转型(upcasting);反之,向下转型(downcasting)。
例1:
public class TestAnimal{
public static void main(String args[]){
Animal a=new Animal("name");
Dog d=new Dog("dogname","black");
Cat c=new Cat("catname","blue");
System.out.println(a instanceof Animal);//true
System.out.println(d instanceof Animal);//true
System.out.println(c instanceof Cat);//true
System.out.println(a instanceof Cat);//false
a=new Dog("bigyellow","yellow");//父类引用指向子类对象(向上转型)
System.out.println(a.name);//bigyellow
//System.out.println(a.furColor);//编译错误:找不到符号!规则(2)
System.out.println(a instanceof Animal);//true
System.out.println(a instanceof Dog);//true!!!
Dog d1=(Dog) a;//强制转换符(向下转型)
System.out.println(d1.furColor);//yellow
//Cat c1=(Cat) a;//运行时抛异常!java.lang.ClassCastException:Dog cannot be cast to Cat
}
} class Animal{
public String name;
Animal(String name){
this.name=name;
}
} class Dog extends Animal{
public String furColor;
Dog(String name,String furColor){
super(name);
this.furColor=furColor;
}
} class Cat extends Animal{
public String eyesColor;
Cat(String name,String eyesColor){
super(name);
this.eyesColor=eyesColor;
}
}
例2:对象转型带来的可扩展性方面的好处
public class TestAnimal{
public static void main(String args[]){
TestAnimal test=new TestAnimal();
Animal a=new Animal("name");
Dog d=new Dog("dogname","black");
Cat c=new Cat("catname","blue");
test.f(a);
test.f(c);
test.f(d);
}
public void f(Animal a){
System.out.println("name:"+a.name);
if(a instanceof Cat){
Cat c1=(Cat) a;
System.out.println(" "+c1.eyesColor+" eyes");
}
else if(a instanceof Dog){
Dog d1=(Dog) a;
System.out.println(" "+d1.furColor+" fur");
}
}
} class Animal{
public String name;
Animal(String name){
this.name=name;
}
} class Dog extends Animal{
public String furColor;
Dog(String name,String furColor){
super(name);
this.furColor=furColor;
}
} class Cat extends Animal{
public String eyesColor;
Cat(String name,String eyesColor){
super(name);
this.eyesColor=eyesColor;
}
}
最新文章
- [转载]网站地址栏小图标favicon.ico的制作方法
- Java/Android 二进制数据与String互转
- adb命令安装apk,和安装问题daemon not running. starting it now on port 5037解决
- BZOJ3641 : 货车运输
- 挑战树莓派:谁才是Geek最爱的开发板?
- OVERLAY代码重入
- C++ 初始化列表(转)
- Office 365 共享链接直接进入编辑
- hello spring春天来了
- 给Ionic写一个cordova(PhoneGap)插件
- Python_tkinter(2)_常用控件
- linux - whatis 提示 ls: nothing appropriate
- C#通过虚方法实现方法重写—多态。
- 【读书笔记】iOS-自定义 URL Scheme 完全指南
- 在Windows7/8/10上,安装IIS
- js设置cookie(原生js)
- openstack 爬坑日记
- os.path等os模块函数
- 【性能测试】:操作NMON的shell脚本
- Python title() 方法
热门文章
- KETTLE 主键不唯一解决方法
- 【VS开发】进程线程及堆栈关系的总结
- Identification of Encryption Algorithm Using Decision Tree
- Python使用pycharm导入pymysql
- php设计模式之注册模式
- 使用Python基于VGG/CTPN/CRNN的自然场景文字方向检测/区域检测/不定长OCR识别
- Robot Framework(三)项目实践出现的问题以及解决方法
- solr学习笔记-导入mysql数据
- python之排序(sort/sorted)
- ccs之经典布局(一)(水平垂直居中)