1.对象的向上转型
2.对象的向下转型
电脑 是 父类 ,笔记本电脑 是 子类,但俗话说 ,笔记本电脑是电脑 就是一种转型。
其实很容易理解 ,张三 是 学生 ,张三 是人。
class Person{
String name;
int age;
void introduce(){
System.out.println("我的姓名是"+name+age);
}
}
class Student extends Person{
String address;
void introduce(){
System.out.println("我的地址是"+address);
super.introduce();//可以不写在第一句
//System.out.println("我的姓名是"+name+age);
}
}
lass Test{
public static void main(String args[]){
Student s = new Student();
Person p = s;
p.name = "zhangsan";
p.age = 21;
p.address = "hubei";
}
}
p.address = "hubei"; 这一句有问题,为什么呢?
注意:一个引用能够调用哪些成员(变量、 函数),取决于这个引用的类型。
所以 Person p 里面 没有address
但是 Test.java中 调用 p.introduce(); 方法,
class Test{
public static void main(String args[]){
Student s = new Student();
Person p = s;
p.name = "zhangsan";
p.age = 21;
//p.address = "hubei";
p.introduce();
}
}
结果是
很显然调用的是 Student 类 中 的introduce(),而不是 Person类 里面的 introduce()
注意:一个引用调用的是哪一个方法,取决于这个引用所指向的对象
可以这样写
//Student s = new Student();
//Person p = s;
Person p = new Student();
总结:一个引用调用的 成员(name 、age、introduce() ) 是父类里面(父类没有address)的 ,而 这个成员 的值(name、age、introduce())是子类里面的。
规范的说 , Person p = new Student () ; 一个引用调用的 成员是Person里面的,而 这个成员 的值是Student里面的。
向下转型
向下转型的前提是 首先 进行 向上转型
错误的向下转型
Person p = new Person();
Student s2 = (Student)p;
因为 张三 、李四 都是 人,但不是 所有的 人都是 张三或者李四 ,所以 人转型 张三 是不可以的 ,先把 张三 转型 人,再把 人转型 张三
TextView textview = (TextView)findViewById(R.id.TextView)