Java学习3-一个类既有父类又实现了接口,那它是什么类型
一个类通常会出现继承了一个类,然后还实现了接口,这个情况在Spring的源码中非常常见。那么这个类到底是什么类型呢?
这个问题其实就是分别属于两中类型,我觉得这就是多态的一种表现。下面就用一个小例子来验证下。
Cat类是Animal的一个子类,但是实现了Pet宠物类这个接口。
public class Cat extends Animal implements Pet{
private String color;
public void print(){
System.out.println("sub class");
}
public Cat(String name,Integer age,String color) throws Exception{
// super(name,age);
// System.out.println(super.getName()+"--------"+super.getClass().getField("color"));
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
下面是测试方法
@Test
public void testMultipleType() throws Exception{
Cat cat = new Cat("aa",12,"red");
if(cat instanceof Animal){
System.out.println("is animal");
}
if(cat instanceof Pet){
System.out.println("is pet ");
}
}
输出结果
/Library/Java/JavaVirtualMachines/jdk1.8.0_241.jdk/Contents/Home/bin/java -ea -
is animal
is pet