面向对象三大特征——多态

多态:相同类型的变量、调用同一个方法时呈现的多种不同的行为特征。要记住Java程序有编译和运行两个过程。
    Human a = new chinese();
    1、编译时类型由声明该变量时使用的类型决定。即Human类型,编译时只能调用该类的方法。
    2、运行时类型由实际赋值给该变量的对象决定。即Chinese类型,运行时可调用继承的方法和该类的方法。
    3、向上自动转型,将子类对象赋给父类引用变量。
强制类型转换:将父类类型的引用变量转换成子类类型,让该引用变量在编译时调用子类的方法。
        1、基本数据类型转换只能在数值类型间进行,如整型,字符型和浮点型。
        2、引用类型间转换只能在具有继承关系的两个类型间进行。
instanceof :判断类型转换是否成功。语法:引用变量 instanceof 类   
              判断前面的对象是否是后面类,或子类的实例。返回true或false。

 1 class HumanTest 
 2 {
 3     public static void main(String[] args)
 4     {
 5         //编译时a是Human类型,运行时a是Chinese类型。
 6         //因为Chinese是Human子类,所以可以直接转换成Human类型
 7         Human a = new Chinese();
 8         a.eat();
 9         System.out.println("a实例地址:"+a);
10         Human b = a;    //Human类型的a 可以直接赋值给Human类型的b
11         Chinese c =(Chinese)a;    //编译时Human类型不能直接转换成Chinese类型,故需要强转。
12         //也可以这样,Chinese c = (Chinese)new Human();
13         //American d = new Chinese();    //报错 Chinese和American不存在继承关系
14         Human hu = new Human();    //报错Human无法直接转换成Chinese
15         System.out.print(hu instanceof Chinese);    //输出false,说明hu不能转换成Chiese类型
16     }
17 }
18 class Human
19 {
20     public void eat(){
21     
22     }
23 }
24 class Chinese extends Human
25 {
26     public void eat(){
27         System.out.println("中国人用筷子吃饭!");
28     }
29 }
30 class American extends Human
31 {
32     public void eat(){
33         System.out.println("美国人用刀叉吃饭");
34     }
35 }
原文地址:https://www.cnblogs.com/manliu/p/3986794.html