Java: 通过继承 class 实现接口
Java: Implementing an interfacing by inheriting a class
适时的问候:)
在 Java 工作,我有一个接口 A。这个接口的所有实现者也扩展了 class B,但是 B 没有实现 A。在我们使用的 class 中A 的实例(引用为 A),它被转换为 B 引用,以便我们可以使用 class B 中定义的方法。从概念上讲,该方法也应该属于接口 A。
你能想出一个理由不把方法引入接口A,这样我们就不用强制转换到接口B了吗?我是否应该覆盖 subclasses 中的方法并只调用超级版本,以便在 IDE 等中更容易导航?
为什么不创建一个扩展 B 并实现 A 的抽象 class?假设此 class 将被称为 C,您的其他 class 将扩展 C 并实现 A 所需的方法,但将为您提供 B 中可用的方法而无需强制转换。
我认为现在移动方法不是一个好主意,也许最多让 B 实现 A(假设你没有其他 class 你没有讨论过的依赖于你提到的 classes 和接口)。
In a class where we use an instance of A (referenced as A), it is cast to a B Reference so that we can use a Method defined in class B.
所以我假设你有这种情况
public void doStuff(A aType){
...
B bType = (B) aType;
...
}
如果这是真的,这行得通吗?
private <T extends B & A> void example(T type){
type.aStuff();
type.doBStuff();
}
我创建了以下内容来对此进行测试。
public class Foo{
private static interface A{
void aStuff();
}
private static class B{
public void doBStuff(){
System.out.println("B stuff");
}
}
private static class AB extends B implements A{
public void aStuff(){
System.out.println("A stuff");
}
}
public static void main(String[] args) {
Foo foo = new Foo();
foo.example(new AB());
}
// method "example" already given
}
给我
A stuff
B stuff
适时的问候:)
在 Java 工作,我有一个接口 A。这个接口的所有实现者也扩展了 class B,但是 B 没有实现 A。在我们使用的 class 中A 的实例(引用为 A),它被转换为 B 引用,以便我们可以使用 class B 中定义的方法。从概念上讲,该方法也应该属于接口 A。
你能想出一个理由不把方法引入接口A,这样我们就不用强制转换到接口B了吗?我是否应该覆盖 subclasses 中的方法并只调用超级版本,以便在 IDE 等中更容易导航?
为什么不创建一个扩展 B 并实现 A 的抽象 class?假设此 class 将被称为 C,您的其他 class 将扩展 C 并实现 A 所需的方法,但将为您提供 B 中可用的方法而无需强制转换。
我认为现在移动方法不是一个好主意,也许最多让 B 实现 A(假设你没有其他 class 你没有讨论过的依赖于你提到的 classes 和接口)。
In a class where we use an instance of A (referenced as A), it is cast to a B Reference so that we can use a Method defined in class B.
所以我假设你有这种情况
public void doStuff(A aType){
...
B bType = (B) aType;
...
}
如果这是真的,这行得通吗?
private <T extends B & A> void example(T type){
type.aStuff();
type.doBStuff();
}
我创建了以下内容来对此进行测试。
public class Foo{
private static interface A{
void aStuff();
}
private static class B{
public void doBStuff(){
System.out.println("B stuff");
}
}
private static class AB extends B implements A{
public void aStuff(){
System.out.println("A stuff");
}
}
public static void main(String[] args) {
Foo foo = new Foo();
foo.example(new AB());
}
// method "example" already given
}
给我
A stuff B stuff