1、这是接口的代码
public interface TestInterface {
String interfacename = print1("接口");
static String print1(String string) {
System.out.println(string+"静态初始化");
return "hello";
};
}
2、这是子类的代码
public class ChildClass extends NormalTest implements TestInterface{
public static String ChildName = print1("child");
public ChildClass() {
System.out.println("ChildClass construtor");
}
}
然后发现报错了,是接口里面已经实现的方法只能在接口里面使用吗,不可以直接调用吗,还是要用到的话要重写?
静态方法调用, 可以使用类名。 静态方法时直接跟类关联的, 子类调用父类的静态方法也是如此
public static String ChildName = TestInterface.print1("child");
另外, 子类不能重写父类的静态方法。 只是会隐藏父类的方法(即子类实例调用同样的静态方法, 该方法触发的是子类的方法。。如果类型是父类, 则调用父类方法)。。跟重写有本质的区别
接口中的静态方法不会被继承,你所做的操作就是调用子类的print方法,但是子类并没继承到这个方法,所以编译失败