Discuss / Java / 有个问题,接口是不是类,在本地找到了编译成.class文件的Income接口。那么实现接口中的方法,是不是就是重写机制。那么接口算不算实现类的父类,但多重实现,java只有单继承关系

有个问题,接口是不是类,在本地找到了编译成.class文件的Income接口。那么实现接口中的方法,是不是就是重写机制。那么接口算不算实现类的父类,但多重实现,java只有单继承关系

Topic source

\oop-interface\bin 的目录

2021/08/31  15:32    <DIR>          .

2021/08/31  15:32    <DIR>          ..

2021/08/31  15:55               419 BaseIncome.class

2021/08/31  15:18               116 Income.class

2021/08/31  15:37               966 Main.class

2021/08/31  15:43               386 RoyaltyIncome.class

2021/08/31  15:43               438 SalaryIncome.class

个人理解,

任何类型的.java的存放源代码的文件,都能被编成.class文件,与对应定义的数据类型无关;

class关键字定义类 ,interface关键字定义接口,所以接口不是类。

我找了下,

https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-9.6.4.4

This behavior differs from Java SE 5.0, where @Override only caused a compile-time error if applied to a method that implemented a method from a superinterface that was not also present in a superclass.

在Java SE 5.0中,@Override仅在应用于从超类中不存在的超接口实现方法的方法时才会导致编译时错误。

关于重写对象的公共方法的子句是由在接口中使用@Override引起的。

For the interface declaration, consider that while an interface does not have Object as a supertype, an interface does have public abstract members that correspond to the public members of Object (§9.2). If an interface chooses to declare them explicitly (that is, to declare members that are override-equivalent to public methods of Object), then the interface is deemed to override them, and use of @Override is allowed.

However, consider an interface that attempts to use @Override on a clone method: (finalize could also be used in this example)

interface Quux { @Override Object clone(); }

对于接口声明,考虑当接口不具有对象作为超类型时,接口确实具有与对象的公共成员(参见9.2)对应的公共抽象成员。如果接口选择显式声明它们(即声明重写等价于对象的公共方法的成员),则该接口将被视为重写它们,并且允许使用@override。

但是,考虑一个试图在克隆方法上使用@覆盖的接口:(在这个例子中也可以使用**finalize**)

也就是说在java 5之后,接口没有父类,允许使用重写覆盖@override。实现接口中的方法,是重写机制。


  • 1

Reply