Animal:
package Aninal;
public class Animal {
public String name;
public Animal(String name) {
this.name = name;
}
}
Cat:
package Aninal;
public class Cat extends Animal{
public String eyecolor;
public Cat(String name, String eyecolor) {
super(name);
this.eyecolor = eyecolor;
}
@Override
public String toString() {
return "我是一只猫"+this.name+"是我的名字,我的眼睛的颜色是"+this.eyecolor;
}
}
Dog:
package Aninal;
public class Dog extends Animal{
public String furcolor;
public Dog(String name, String furcolor) {
super(name);
this.furcolor = furcolor;
}
@Override
public String toString() {
return "我是一只狗,"+this.name+"是我的名字,我的毛色是"+this.furcolor;
}
}
test:
package Aninal;
import org.junit.Test;
public class Jtest {
@Test
public void test(){
Animal a=new Animal("woshidongwu");
Dog d=new Dog("金毛","yellow");
Cat c=new Cat("咖啡猫","咖啡色");
System.out.println(a instanceof Animal);
System.out.println(c instanceof Animal);
System.out.println(d instanceof Animal);
System.out.println(a instanceof Dog);
}
@Test
public void test1(){
Animal a=new Dog("金毛","yellow");
System.out.println(a.name);
System.out.println(a instanceof Animal);
Dog d=(Dog) a;
System.out.println(d.furcolor);
}
@Test
public void test2(){
Animal a=new Animal("我是动物");
Dog d=new Dog("金毛", "yellow");
Cat c=new Cat("萨摩耶", "white");
match(a);
match(d);
match(c);
}
private void match(Animal animal){
System.out.println("名称:"+animal.name);
if(animal instanceof Cat){
Cat cat=(Cat) animal;
System.out.println("眼睛颜色:"+cat.eyecolor);
}else if(animal instanceof Dog){
Dog dog=(Dog) animal;
System.out.println("毛发颜色:"+dog.furcolor);
}
}
}