/*多态的前提:
* 子父类的继承关系
* 方法重写
* 父类引用指向子类对象
*
* 动态绑定:运行期间(run的时候):运行时期调用的方法,是根据其具体的类型
* */
public class PoymrphicDemo {
public static void main(String[] args) {
Cat c = new Cat();
c.eat();
/*父类引用 Animal a
指向 =
子类对象new Cat()
*/
Animal a = new Cat();
a.eat();
}
}
class Animal{
public void eat()
{
System.out.println("吃东西");
}
}
class Cat extends Animal{
public void eat()
{
System.out.println("猫吃鱼");
}
}
/*
* 多态的成员特点:
* 成员变量:编译时看的是左边,运行时看的是左边 因为变量没有重写的概念
* 成员方法 编译时看左边 运行时看右边
* 静态方法 编译时看左边 运行时看左边 因为使用变量去调用静态方法,相当于用变量类型的类名去调用
* 总结:编译时看的都是左边 运行时成员方法看的是右边 其他(成员变量和静态方法)看的是左边*/
public class PoymrphicDemo2 {
public static void main(String[] args) {
Dad d = new kid();
d.method();
System.out.println();
System.out.println();
}
}
class Dad {
int num = 20;
public void method()
{
System.out.println("我是父类方法");
}
public static void function()
{
System.out.println("我是父类静态方法");
}
}
class kid extends Dad{
int num = 10;
public void method()
{
System.out.println("我是子类方法");
}
public static void function()
{
System.out.println("我是子类静态方法");
}
}
/*
* 多态中的向上转型和向下转型
* 1 向上转型 自动的 由小到大(父类型转换成子类型)
* 2 向下转型 强制的 由大到小*(子类型转化成父类型)*/
public class PoymorphicDemo3 {
public static void main(String[] args) {
Animal2 a = new Dog();//向上转型
a.eat();
Dog d = (Dog)a; //向下转型
d.swim();
}
}
class Animal2
{
public void eat()
{
System.out.println("吃东西");
}
}
class Dog extends Animal2{
public void eat()
{
System.out.println("啃骨头");
}
public void swim()
{
System.out.println("狗刨");
}
}
/*
* 多态的优缺点:
* 优点:可以提高可维护性(多态前提所保证的) 提高代码的可拓展性
* 缺点:无法直接访问子类特有的成员
* */