多态的前提:
动态绑定:运行期间调用的方法,是根据具体的类型,具体的方法 优缺点:
package com.a2data;
/**
* Created by JackFeng on 2020/3/15.
*/
public class PoymorphicDemo {
public static void main(String[] args) {
// Cat cat = new Cat();
// cat.eat();
// 父类引用 Animal a
// 指向 =
// 子类对象 new Cat()
// 动态绑定
Animal a = new Cat();
a.eat();
}
}
class Animal {
public void eat(){
System.out.println("c吃东西");
}
}
class Cat extends Animal{
public void eat(){
System.out.println("猫吃鱼");
}
}
多态的成员特点:
编译时看的都是左边,运行时成员方法看的是右边,其他(成员变量和静态方法)看的都是左边
package com.java;
import java.util.Date;
/**
* Created by JackFeng on 2020/3/15.
*/
public class PoymorphicDemo {
public static void main(String[] args) {
// 成员变量
// 在继承中没有被重写的概念,没有动态绑定的概念
// 执行的是父类的
Dad d = new Kid();
System.out.println(d.num);
// 成员方法
// 运行看右边
System.out.println("----------");
d.method();
// 静态方法
d.function(); // 使用变量去调用静态方法,相当于用变量类型的类名去调用 所以输出父类的静态方法
}
}
class Dad{
int num = 1;
public void method(){
System.out.println("我是父类的方法");
}
public static void function(){
System.out.println("我是父类的静态方法");
}
}
class Kid extends Dad{
int num = 21;
public void method(){
System.out.println("我是子类的方法");
}
public static void function(){
System.out.println("我是子类的静态方法");
}
}
多态中的向上转型和向下转型:
package com.java;
/**
* Created by JackFeng on 2020/3/15.
*/
public class polymorphicDemo {
public static void main(String[] args) {
Animal a = new Dog(); // 向上转型
a.eat();
Dog d = (Dog) a; // 向下转型 本身是什么类型 转换成什么类型
d.swim();
}
}
class Animal{
public void eat(){
System.out.println("吃东西");
}
}
class Dog extends Animal{
public void eat(){
System.out.println("啃骨头");
}
public void swim(){
System.out.println("狗刨");
}
}