看了尚学堂视频除了问题
package com.ch3;
public class Animal {
public String name;
public Animal(String name){
name=this.name;
}
}
package com.ch3;
public class Cat extends Animal {
public String eyeColor;
public Cat(String name,String eyeColor){
super(name);
eyeColor=this.eyeColor;
}
}
package com.ch3;
public class Dog extends Animal {
public String furColor;
public Dog(String name, String furColor) {
super(name);
furColor = this.furColor;
}
}
package com.ch3;
public class TestAnimal {
public static void main(String[] args){
TestAnimal test =new TestAnimal();
Cat cat=new Cat( "catname ", "redEye ");
test.f(cat);
}
public void f(Animal a){
System.out.println( "Name: "+a.name);
if(a instanceof Cat){
Cat cat=(Cat)a;
System.out.println( "EyeColor: "+cat.eyeColor);
}else if(a instanceof Dog){
Dog dog=(Dog)a;
System.out.println( "FurColor: "+dog.furColor);
}
}
}
这是我在尚学堂看到老师的一个视频,然后模拟写了一个类似的,但是结果不是我想到的那种,结果是:
Name:null
EyeColor:null
我对了几遍,都看不出来,好郁闷啊!
------解决方案--------------------package com.ch3;
public class Animal {
public String name;
public Animal(String name){
name=this.name;
}
}
package com.ch3;
public class Cat extends Animal {
public String eyeColor;
public Cat(String name,String eyeColor){
super(name);
this.eyeColor = eyeColor;
}
}
package com.ch3;
public class Dog extends Animal {
public String furColor;
public Dog(String name, String furColor) {
super(name);
this.furColor = furColor;
}
}
package com.ch3;
public class TestAnimal {
public static void main(String[] args){
TestAnimal test =new TestAnimal();
Cat cat=new Cat( "catname ", "redEye ");
test.f(cat);
}
public void f(Animal a){
System.out.println( "Name: "+a.name);
if(a instanceof Cat){
Cat cat=(Cat)a;
System.out.println( "EyeColor: "+cat.eyeColor);
}else if(a instanceof Dog){
Dog dog=(Dog)a;
System.out.println( "FurColor: "+dog.furColor);
}
}
}