Java多态的基本使用

//多态的其他使用
public class Test {
public static void main(String[] args) {
//a变量数据类型为Animal,是Dog类的父类型
//方法调用时: 编译看左边,运行看右边
//意思是进行编译函数的时候会先在左边的类型(Animal)中查找是否有这个方法,如果有再到右边的类型(Dog)中运行被重构的方法,如果未找到方法就会报错
//因为方法编译看左边的特性,如果调用方法时,左边类中没有,而右边类中有这个方法。因为编译看的是左边的类,所以右边的方法也无法被找到
Animal a = new Dog();
a.show(); //调用Dog中被重写的show方法
// a.eat(); 报错的代码,因为编译时在左边的Animal类中未发现这个方法

Animal b = new Cat();
b.show(); //调用Cat中被重写的show方法

//变量调用时: 编译看左边,运行也看左边
//如果左边的类中没有这个变量,那么这个变量将无法被找到
System.out.println(a.a); //a变量在Animal中可以被找到并编译,正常输出100
// System.out.println(a.b); //b变量在右边的Dog类中,无法被找到无法被编译,报错
System.out.println(b.a); ////a变量在Animal中可以被找到并编译,正常输出100

//=======================================================================
//解决方法也很简单,直接转换为子类的数据类型即可
Dog d = (Dog) a;
Cat c = (Cat) b;

d.eat();
c.eat();
}
}

class Animal {
//动物类
private String type = "动物";
int a = 100;

public Animal() {

}

public Animal(String type) {
this.type = type;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public void show() {
System.out.println("动物类型为" + this.type);
}
}

class Dog extends Animal {
int b = 200;

public Dog() {
super("狗狗"); //调用父类构造函数
}

public void eat() {
System.out.println(super.getType() + "正在吃骨头");
}

@Override
public void show() {
System.out.println("动物类型为" + super.getType());
}
}

class Cat extends Animal {
int c = 300;

public Cat() {
super("猫猫"); //调用父类构造函数
}

public void eat() {
System.out.println(super.getType() + "正在吃猫粮");
}

@Override
public void show() {
System.out.println("动物类型为" + super.getType());
}
}