java基础---对象的转型
2013-10-01 20:23
363 查看
向上转型--将子类的对象赋值给父类的引用
Student s = new Student();
Person p = s;
父类:
子类:
主函数:
需要记住的语法要点:
1、一个引用能够调用哪些成员(变量和函数),取决于这个引用的类型
Eg:p.address 是错误的,因为person没有这个成员变量,所以无法调用。
2、一个引用调用的是哪一个方法,取决于这个引用所指向的对象
Eg:p.introduce()调用的其实是student中的introduce
向下转型---将父类的对象赋值给子类的引用
Student s1 = new Student();
Person p = s1; //向上转型
Student s2 = (Student)p; //这就是向下转型
错误的向下转型的例子:
Person p = new Person();
Student s = (Student)p; //无法将一个父类生成的引用直接向下转成子类
Student s = new Student();
Person p = s;
父类:
class Person{ String name; int age; void introduce(){ System.out.println("我的名字" + name + "我的年龄" + age); } }
子类:
class Sutdent extends Person{ String address; void introduce(){ super.introduce(); System.out.println("我的家在" + address); } }
主函数:
class Test{ public static void main(String args []){ Student s = new Student(); Person p = s; } }
需要记住的语法要点:
1、一个引用能够调用哪些成员(变量和函数),取决于这个引用的类型
Eg:p.address 是错误的,因为person没有这个成员变量,所以无法调用。
2、一个引用调用的是哪一个方法,取决于这个引用所指向的对象
Eg:p.introduce()调用的其实是student中的introduce
向下转型---将父类的对象赋值给子类的引用
Student s1 = new Student();
Person p = s1; //向上转型
Student s2 = (Student)p; //这就是向下转型
错误的向下转型的例子:
Person p = new Person();
Student s = (Student)p; //无法将一个父类生成的引用直接向下转成子类
相关文章推荐
- java基础总结13-面向对象9(对象转型)
- JAVA基础-- 对象转型 (casting)
- 【JAVA基础知识总结】-JAVA对象转型(转)
- java基础学习总结——对象转型
- 2018/01/07JAVA 基础 / 接口与继承:对象转型的意义、instanceof的语法
- 再学 JAVA基础(5)对象转型,多态。【子类对象的实例化过程】
- java基础之对象的向上转型
- java面向对象基础(三):对象转型和多态
- java基础--对象转型和多态
- java基础8_对象转型_接口
- 黑马程序员_Java基础_03面向对象思想(对象转型注意事项、多态、抽象类、final关键字等)
- java基础之对象的向下转型
- java基础学习总结——对象转型
- java基础学习总结——对象转型
- JAVA基础6.50——对象转型
- java基础学习总结——对象转型
- java基础学习总结——对象转型
- java基础----对象的上转型对象