java基础--对象转型和多态
2013-03-30 22:33
489 查看
对象转型(casting):
1、一个基类的引用类型变量可以是指向子类的对象。
2、一个基类引用不能访问子类对象新增加的成员(属性和方法)。
3、可以使用引用变量instaceof来判断该引用类型变量所“指向”的对象是否属于该类,或者该类的子类。
4、 子类对象可以作为基类对象使用,称为(upcasting)“向上转型”,基类对象当做来使用称为(downcasting)“强制转换”。
例如,代码如下:
内存分析:
父类引用指向子类的对象,只能看到父类的那部分,看不到子类的那部分。a只能看到名字。
强制转换后(向下转型)可以看到全部的内容。
很基础的东西,但很重要。
1、一个基类的引用类型变量可以是指向子类的对象。
2、一个基类引用不能访问子类对象新增加的成员(属性和方法)。
3、可以使用引用变量instaceof来判断该引用类型变量所“指向”的对象是否属于该类,或者该类的子类。
4、 子类对象可以作为基类对象使用,称为(upcasting)“向上转型”,基类对象当做来使用称为(downcasting)“强制转换”。
例如,代码如下:
Class Animal { Public String name; //构造函数。 Animal(String name) { This.name = name; } } Class Cat extends Animal { Public String eyesColor; Cat(String n, String c) { Super(n); eyeColor = c; } } Class Dog extends Animal { Public String furColor; Dog(String n, String c) { Super(n); furColor(c); } }
Pulic class Test { Public static void main(String args[]) { Animal a = new Animal("name"); Cat c = new Cat("Catname","blue"); Dog d = new Dog("dogname","black"); System.out.println(a instanceof Animal); System.out.println(c instanceof Animal); System.out.println(d instanceof Animal); System.out.println(a instanceof Cat); A = new Dog("bigyellow","yellow"); System.out.println(a.name); System.out.println(a.furname); System.out.println(a instanceof Animal); System.out.println(a instanceof Dog); Dog d1 = (Dog)a;//强制转换符。 System.out.println(d1.furColor); } }
内存分析:
父类引用指向子类的对象,只能看到父类的那部分,看不到子类的那部分。a只能看到名字。
强制转换后(向下转型)可以看到全部的内容。
很基础的东西,但很重要。
相关文章推荐
- 黑马程序员_Java基础_03面向对象思想(对象转型注意事项、多态、抽象类、final关键字等)
- java面向对象基础(三):对象转型和多态
- 再学 JAVA基础(5)对象转型,多态。【子类对象的实例化过程】
- java基础学习之对象转型
- 复习之java基础---->多态:向上转型
- Java基础笔记整理---【09】面向对象程序设计-上转型对象
- java基础学习总结——对象转型
- 黑马程序员——Java基础---面向对象之多态抽象类接口
- 黑马程序员_java基础3-面向对象(二)多态、异常、包
- java基础学习总结——对象转型
- java基础8_对象转型_接口
- java基础---对象的转型
- Java 多态运行顺序&&多态上转型对象
- 黑马程序员 java基础复习三之对象初始化,多态和异常等
- [Java][视频] 笔记-对象转型 和 动态绑定(多态)
- 【JAVA基础知识总结】-JAVA对象转型(转)
- java多态与对象转型
- java基础整理——父类引用指向子类对象实体的多态
- Java基础之面向对象的方法参数和对象上转型