多态:一种事物的多种形态
* 多态的规则(前提):1.类与类之间要建立关系,建立继承的关系2.必须要有方法的重写3.要有父类的指针(引用)指向子类的对象(空间)
public static void main(String[] args) {
//本类的指针(引用)指向了子类的对象(空间)
Cat cat = new Cat();
cat.eat();
//猫是一只动物(不能动物是一只猫)
//父类的指针指向子类的对象
Animal animal = new Cat();
animal.eat();
Animal animal2 = new Dog();
animal2.eat();
}
}
//需求:创建动物类,猫类,狗类
class Animal
{
public void eat()
{
System.out.println("吃饭");
}
}
class Cat extends Animal
{
@Override //重写
public void eat() {
// TODO Auto-generated method stub
super.eat();
System.out.println("吃鱼");
}
}
class Dog extends Animal
{
@Override//重写
public void eat() {
// TODO Auto-generated method stub
super.eat();
System.out.println("吃骨头");
}
多态时 成员变量是如何调用的?
*多态时,当父类引用调用成员变量的时候,编译需要看父类中有没有这个成员变量,没有编译不会通过,运行时访问的是父类中的成员变量
*多态时,父类对象访问成员变量,编译和运行时都看父类
*多态时,父类对象访问成员方法,编译的时候看父类中有没有这个方法,没有就报错,运行时运行的是子类中的方法,子类的方法入栈,(编译看父类,运行看子类)
public static void main(String[] args)
{
Father father = new Son();
//编译的时候是看父类中是否有该方法,运行时运行的是子类的方法
father.say();
System.out.println(father.num);
Son son = new Son();
System.out.println(son.num);
}
}
class Father
{
int num = 10;
public int getNum()
{
return num;
}
public void say()
{
System.out.println("Father说");
}
}
class Son extends Father
{
int num = 20;
public int getNum()
{
return num;
}
// @Override
// public void say() {
// // TODO Auto-generated method stub
// System.out.println("Son说");
// }
多态的好处:1.增强了代码的可维护性(建立在继承的基础上)2.增强方法的可扩展性(核心)
* 多态的弊端:不能直接调用子类的特殊方法(不是重写父类的)
public static void main(String[] args)
{
//向上转型
People p1 = new Cheater();
//骗子调用自己的方法
p1.say();
//向下转型,注意:如果你要向下转型,必须之前有过向上转型
Cheater cheater = (Cheater)p1;
cheater.hit();
}
}
class People
{
String name;
int age;
public void say()
{
System.out.println("聊天");
}
}
class Cheater extends People
{
@Override// 重写
public void say() {
// TODO Auto-generated method stub
System.out.println("洗脑");
}
public void hit()
{
System.out.println("打你");
}