对象的转型
来源:互联网 发布:js如何验证身份证号码 编辑:程序博客网 时间:2024/05/22 21:05
主要内容:
1.对象的向上转型
举个例子:
原因:一个引用调用的是那一个方法,取决于这个引用所指向的对象。从上面可知,这个对象是Student。
1.对象的向上转型
2.对象的向下转型
什么是向上转型?
向上转型:将子类的对象赋值给父类的引用。
Student s = new Student();
Person p = s;
要进行向上转型,必须student和Person要有继承关系。
class Person{ static String name; int age; void introduce(){ System.out.println("我的名字是"+name+"我的年龄是"+age); }}class Student extends Person{ String address; void introduce(){//复写 super.introduce(); System.out.println("我的地址是"+address); }}class Test3{ public static void main(String agrs[]){ Student s = new Student(); Person p = s;//向上转型 }}注意:一个引用能够调用哪些成员(变量和函数),取决于这个引用的类型(决定于这个类型中有无相应的变量和函数),不管你有无进行向上转型。
举个例子:
class Test3{ public static void main(String agrs[]){ Student s = new Student(); Person p = s;//向上转型//person p = new Student();//向上转型也可以这样写 p.name = "张三"; p.age = 20; p.address = "北京";//报错。虽然进行了向上转型但是在Person类中没有address这个变量 }}如果使用p.introduce() 发现调用的是子类的introduce的方法,父类和子类都有这个方法,为什么会调用子类的呢?这是为什么?
原因:一个引用调用的是那一个方法,取决于这个引用所指向的对象。从上面可知,这个对象是Student。
向下转型:
向下转型:将父类的对象赋值给子类的引用。
Student s1 = new Student();
Person p = s1;//向上转型
Student s2 = (Student)p;//向下转型
向下转型的前提是向上转型。
- 对象的转型
- 关于对象的转型
- 对象的转型
- 对象的转型
- 7、对象的转型
- 对象的转型
- 对象的转型_21
- Java4Android-对象的转型
- 对象的转型
- #java#对象的转型
- java21对象的转型
- 对象转型的例子
- 对象的向上转型和向下转型
- 对象的转型(向上向下转型)
- 对象的上转型对象
- 对象的上转型对象
- 对象的上转型对象
- 对象的上转型对象
- ArcGIS.Server.9.3和ArcGIS API for JavaScript实现语句查询QueryTask(八)
- Frankenstein——15
- unity3d Photon跨平台开发有那些解决方案
- GTK+中的插件
- ArcGIS.Server.9.3和ArcGIS API for JavaScript实现距离量算和面积量算(九)
- 对象的转型
- 记下另一种获取状态等UUID相关信息的方法
- varchar和Nvarchar区别
- javaScript string.replace只能替换一个(解决)
- Centos6.2下的精装伴侣:Raknet & Code::Blocks 安装方法实操指引
- Win7下Xamarin的安装
- ArcGIS.Server.9.3和ArcGIS API for JavaScript保存自定义图形(十)
- Ural 1326
- MFC消息映射及MFC入门