以下是一个示例课程设计,我希望能帮助我提出这个问题:
public interface Foo
{
int someMethod();
}
public abstract class Bar implements Foo
{
public int someMethod()
{
return 1;
}
}
public class Baz extends Bar
{
}
public class Quz extends Bar
{
public int someMethod()
{
return 2;
}
}
public class Norf extends Baz
{
public static void main(String[] args)
{
Foo[] arr = new Foo[4];
// Some code to take advantage of polymorphism
}
}
在Norf
类中,我创建了一个类型为Foo
的多态数组(这是一个接口)。我试图理解允许哪些类成为该数组的成员/元素的对象。
根据我的理解,如果你正在创建一个类的多态数组,那么从它的子类(继承树中的任何后代)创建的任何对象都可以是这个数组的成员。
我正在尝试为接口的多态数组制定规则。
回到示例类设计,以下似乎是有效的(我在我的IDE中键入了它并且没有抱怨)
arr[0] = new Baz();
arr[1] = new Quz();
arr[2] = new Norf();
因此,看起来任何实现接口的非抽象类的对象或其任何具体子类都可以是此数组的成员。
我有什么遗漏或可以添加到上述规则中的任何内容吗?
答案 0 :(得分:2)
扩展@karthik的答案,任何实现Foo
的实例都可以是数组的元素。并且一个类直接或间接地通过作为实现它的类的后代或通过作为实现它的类的后代的后代等来实现Foo
等。
或者也可能发生接口扩展Foo
然后类实现此子接口;那么这样一个类的实例作为数组元素也是有效的:
public interface SubFoo extends Foo { }
public class Blablab implements SubFoo {
public int someMethod() {
return 3;
}
}
一些例子:
Foo[] arr = new Foo[7];
arr[0] = new Baz();
arr[1] = new Quz();
arr[2] = new Norf();
arr[3] = () -> 7; // As Foo has only one method, lambdas are allowed as well
arr[4] = new Bar() {}; // Anonymous classes are also allowed
arr[5] = new SubFoo() { public int someMethod() { return 123; } };
arr[6] = new Blablab();
答案 1 :(得分:1)
任何实现Foo
接口的类或任何扩展类的类都可以直接或间接地实现Foo
。
在你的情况下
arr[0] = new Baz(); // Baz extends Bar and Bar implements Foo
arr[1] = new Quz(); // Quz extends Bar and Bar implements Foo
arr[2] = new Norf(); // Norf extends Baz, Baz extends Bar and Bar implements Foo
如果你绘制一种树状结构
Foo
|
Bar
/ \
Baz Quz
/
Norf
您直接或间接定义的所有类都实现了接口Foo
,因此可以添加所有类。