对象向上转型与向下转型

来源:互联网 发布:java工资扣培训费 编辑:程序博客网 时间:2024/05/21 11:07

今天 看了一下对象的转型方面的知识,有了一点点更加清楚的收获:

首先我们新建一个Person类,代码如下:

package com.test;public class Person {  String Name;  String Age;  void Introduce(){  System.out.println("我的姓名是"+Name+"我的年龄是"+Age);  }}

学生类的代码如下:

package com.test;public class Student extends Person{ String Address;   void Introduce() { super.Introduce();System.out.println("我的家住在"+Address);}void Study(){System.out.println("我正在学习");}}
测试类的代码如下:

package com.test;public class Test {/** * @param args */public static void main(String[] args) {Student student=new Student();student.Name="张三 ";student.Age="20";student.Address="广州";Person person=student;person.Introduce();}}
我们运行的结果如下:

我的姓名是张三 我的年龄是20
我的家住在广州

//////////////////////////////////////////////////////////////////////////////////////////////////////////

针对上面的结果,我们总结如下,内容:

1、如果我们调用person.Address的话就会报错,因为:一个引用能够调用哪些成员(变量,和函数)取决于这个引用的类型!

2、上面的Test中我们调用person.Introduce();这个方法打印的结果有:我的家住在广州这表明person调用的Introduce()方法是Students中的!

所以我们可以明白,一个引用可以调用哪些方法取决于这个引用所指向的对象!


原创粉丝点击