代码如下:
package hellojava;
public class hello{
public class Animal {
public void eat() {}
}
public class Horse extends Animal {
public void eat(String food) {}
}
public class UseAnimals {
public void doStuff(Animal a) {
System.out.println("Animal");
}
public void doStuff(Horse h) {
System.out.println("Horse");
}
}
public static void main (String [] args) {
UseAnimals ua = new UseAnimals();
Animal animalobj = new Animal();
Horse horseobj = new Horse();
Animal animalRefToHorse = new Horse();
ua.doStuff(animalobj);
ua.doStuff(horseobj);
ua.doStuff(animalRefToHorse);
}
}
我的原意是测试:
这张图的意思是不是说,前面定义了一个变量的引用类型,为Animal;后面赋给这个变量实质的实例类型,为Horse。
但是他的类型还是算Animal??
结果出现了意想不到的错误
静态编译时,报错
No enclosing instance of type hello is accessible. Must qualify the allocation with an enclosing instance of type hello (e.g. x.new A() where x is an instance of hello).
原来是因为:
在一个类的静态成员中去访问非静态成员之所以会出错是因为在类的非静态成员不存在的时候静态成员就已经存在了,访问一个内存中不存在的东西当然会出错。
所以给三个类加上static修饰符之后,可以运行
Animal
Horse
Animal
运行结果证明,类型还是算Animal