java知识之面向对象
面向对象三大特征:继承(Inheritence)、封装(Encapsulation)、多态(Polymorphism)
前几讲写了继承与封装,接下来介绍多态
多态
多态:父类型的引用可以指向子对象。
例子1:
public class Test {
public static void main(String[] args) {
/*Son son=new Son();
son.color(); //输出结果为:Yellow is a color
*/
/*
* Father father=new Father();
father.color(); //输出结果为:Red is a color
*/
Father f=new Son();
f.color();
}
}
class Father{
public void color(){
System.out.println("Red is a color");
}
}
class Son extends Father{
public void color(){
System.out.println("Yellow is a color");
}
}
输出结果:
Yellow is a color
Father f=new Son(); f类型是父类型,看类型是左边的那个Father指向了子类生成的属性,接下来调用color()方法,指向Son(),就调用子类的方法,所以输出子类的方法,指向谁就调用谁的方法。
例子2:
public class Test {
public static void main(String[] args) {
Father father=new Son();
father.color();
}
}
class Father{
//方法体为空
}
class Son extends Father{
public void color(){
System.out.println("Yellow is a color");
}
}
可以看出这个报错,说明:father是指向子类对象的引用,但是father还是Father类型的,而Father中没有这个方法,对于多态可以这样理解,即便是father是指向子类,但是必须在father所在Father中必须存在这个方法,才可以调用。father在调用子类的方法的时候,会去检查father所在类型是否有这个方法,如果有的话,就调用子类的这个方法,否则报错。
例子3:
public class Test {
public static void main(String[] args) {
/*
Father f=new Daughter();
Daughter d= (Daughter)f;
d.color();//输出Orange is a color
*/
Father f=new Son();
Son s= (Son)f;
s.color();
}
}
class Father {
public void color(){
System.out.println("Red is a color");
}
}
class Daughter extends Father{
public void color(){
System.out.println("Orange is a color");
}
}
class Son extends Father{
public void color(){
System.out.println("Yellow is a color");
}
}
输出结果:
Yellow is a color
分析:Father f=new Son(); Son s= (Son)f;这两条语句是一个强制类型转换,将一个父类型的引用强制给子类型的引用,这在多态中叫做向下类型转换,注意的是它实际指向的是谁,才能转换的谁。比如f实际指向的是Son对象,所以才能强制转换为Son类型的引用。
注意:一共有两种类型的强制转换
1) 向上类型转换(upcast):比如说将Son类型的转换为Father类型,即将子类转换为父类型。
2)向下类型转换(downcast):比如将Father类型转换为Son类型,即将父类型转换为子类型。对于向下,必须要显式指定(必须要使用强制类型转换)。
例子4:
//向上转换类型
Son s=new Son();
Father f=s;
f.color();
//向下转换类型
Father f=new Son();
Son s=(Son)f;
s.color(); //此时的f.color();这两个执行效果一样
为什么还要做这种向下类型转换呢?
比如说父类中3个方法,子类继承了或者重写了父类的三个方法,此时使用向下类型转换意义不大,因为调用使用与不使用都是调用子类这三个方法一个。但是有一种情况是,假如这个子类自己添加了5个方法,此时父类有3个方法,子类有8个方法,此时如果调用f.color();这种方法时只能调用在子类当中存在于父类当中的那三个方法,其他五个方法是没法调用到的,因为f是父类型,所以只能调用父类型中有的方法,此时如果使用向下转型之后,调用s.color();此时s是属于子类型的,所以可以调用子类当中的所有方法,这就是使用向下类型转换的原因。
例子5:
public class Test {
public static void main(String[] args) {
Father f=new Son();
Son s=(Son)f;
s.eat();
}
}
class Father {
public void color(){
System.out.println("Red is a color");
}
public int eat(){
System.out.println("I like eating some food");
return 0;
}
}
class Daughter extends Father{
public void color(){
System.out.println("Orange is a color");
}
}
class Son extends Father{
public void color(){
System.out.println("Yellow is a color");
}
}
输出结果:
I like eating some food