新人,请教一个java小问题
class Animal {
public String name;
Animal(String name) {
this.name = name;
}
}
class Cat extends Animal{
public String eyecolor;
Cat(String name,String eyecolor) {
super(name);
this.eyecolor = eyecolor;
}
}
class Dog extends Animal{
public String furcolor;
Dog(String name,String furcolor) {
super(name);
this.furcolor = furcolor;
}
}
public class TestCasting1 {
public static void main(String[] args) {
Animal a = new Animal("gaga");
Cat c = new Cat("mimi","blue");
Dog d = new Dog("wangwang","black");
a.test(a);
c.test(c); //为什么反应找不到符号?
d.test(d);
//TestCasting1.test(a);
//TestCasting1.test(c);
//TestCasting1.test(d);
}
//public static void test(Animal a) {
public void test(Animal a) {
if(a instanceof Animal) {
System.out.println(a.name);
if (a instanceof Cat) {
Cat cat = (Cat) a;
System.out.println(cat.eyecolor);
} else
if (a instanceof Dog) {
Dog dog = (Dog) a;
System.out.println(dog.furcolor);
}
}
}
}
为什么编译时会报:a.test(a);
c.test(c);
d.test(d);
这三个找不到符号?
------解决方案--------------------你的test()方法是定义在TestCasting1里面的,而animal,cat,dog类中不存在此方法。所以构造出的对象无法调用,结果就是找不到了。
------解决方案--------------------Java code
public static void main(String[] args) {
Animal a = new Animal("gaga");
Cat c = new Cat("mimi", "blue");
Dog d = new Dog("wangwang", "black");
TestCasting1 test = new TestCasting1();
test.test(a);
test.test(c); // 为什么反应找不到符号?
test.test(d);
// TestCasting1.test(a);
// TestCasting1.test(c);
// TestCasting1.test(d);
}
------解决方案--------------------
test方法属于TestCasting1成员方法,使用时创建 new TestCasting1()再使用,除此其他类均无此方法,你怎么调用呢?
[size=16px]
Java code
public static void main(String[] args) {
Animal a = new Animal("gaga");
Cat c = new Cat("mimi", "blue");
Dog d = new Dog("wangwang", "black");
TestCasting1 test = new TestCasting1();
test.test(a);
test.test(c);
test.test(d);
}