1.首先,我们都知道子类继承父类会继承父类的public 和 protected属性和方法。
2.接下来我有个疑问,父类继承了一个祖父类,子类再继承父类,子类继承祖父类吗?
先说答案,是的,子类也会继承祖父类
//祖父类
public class grandFather {
}
//父类继承祖父类
public class father extends grandFather{
}
//现在子类继承父类
public class child extends father{
public static void main(String[] args) {
//采用instanceof关键字判断child的类型
child c = new child();
boolean is = c instanceof grandFather;
System.out.println("child 是不是 grandFather 类型:"+is);
}
}
3.既然类的继承可以传递下来,那接口的实现可以传递下来吗?
先说结果,可以,子类自动实现父类实现的接口,可以不用显式的写出implements,系统也会承认
//现在有个接口
public interface testInterface {
}
//父类继承了这个接口
public class father implements testInterface{
}
//子类继承父类
public class child extends father{
public static void main(String[] args) {
//采用instanceof关键字判断child的类型
child c = new child();
boolean is = c instanceof testInterface;
System.out.println("child 是不是 testInterface 类型:"+is);
}
}
这里如果还不确定,我再举个例子:
//创建线程有个方法,就是
//把实现了Runnable接口的一个类的对象作为靶子
//创建线程
java.lang.Thread.Thread(Runnable target);
//这里面的参数必须是一个实现了Runnable接口的类的对象
//现在有java自带的一个线程接口Runnable
public interface Runnable(){
}
//父类实现Runnable接口
public class father implements Runnable{
//实现这个接口要实现run方法,不用写什么,空着就行
@Override
public void run(){
}
}
//子类继承父类
public class child extends father{
public static void main(String[] args) {
//我们来利用child对象和father对象创建线程看看
child c = new child();
father f = new father();
new Thread(c);
new Thread(f);
}
}
唉,是没有报错的,说明child也实现了Runnable接口——虽然没有显式implements出来。
这是我另一个关于接口的文章:接口继承小记