1、多态的前提
1)有继承/实现关系
2)有方法重写
3)有父类引用指向子类对象
2、编译看左边,运行看右边
编译(compilation,compole)
1)利用编译程序从源语言编写的源程序产生目标程序的过程
2)用编译程序产生目标程序的动作
编译就是把高级语言变成计算机可以识别的2进制语言,计算机只认识1和0,编译程序把人们熟悉的语言换成2进制的。编译程序把一个源程序翻译成目标程序的工作过程分为五个阶段:语法分析;词法分析;语义检查和中间代码生成;代码优化;目标代码生成。主要是进行语法分析和词法分析,又称为源程序分析,分析过程中发现有语法错误,给出提示信息。
判断编译是否成功,看是否出现红色提示!
多态中成员访问特点
成员变量:编译看左边,运行看左边
成员方法:编译看左边,运行看右边
因为成员方法有重写,成员变量没有!
范例:猫和动物
public class Animal { public int age=40; public void eat(){ System.out.println("动物吃东西"); } }
public class Cat extends Animal{ public int age=20; public int weight=10; @Override public void eat() { System.out.println("猫吃鱼"); } public void playGame(){ System.out.println("猫捉迷藏"); } }
public class AnimalDemo { public static void main(String[] args) { Animal a=new Cat(); System.out.println(a.age); // System.out.println(a.weight); a.eat(); //成员方法eat猫重写父类动物 // a.playGame(); } }
3、多态的弊端:不能访问子类的特有功能
解决:多态的转型
public class Animal { public void eat(){ System.out.println("动物吃东西"); } }
public class Cat extends Animal{ @Override public void eat() { System.out.println("猫吃鱼"); } public void platGame(){ System.out.println("猫捉迷藏"); } }
public class AnimalDemo { public static void main(String[] args) { Animal a=new Cat(); a.eat(); // a.playGame(); Cat c=(Cat)a; //向下转型 c.eat(); c.platGame(); //可以访问子类猫类的方法 } }