为什么喜欢构图而不是继承呢?每种方法都有哪些权衡取舍?什么时候应该选择继承而不是作文?
当我在以下代码中声明数组时,我无法理解实际发生的情况.
class Type1 {
}
class Type2 extends Type1 {
public void method2() {
}
}
class Test {
public static void main(String[] args) {
Type1[] x = new Type2[2];
x[0] = new Type1(); // runtime error
x[1] = new Type2();
x[1].method2(); // syntax error
}
}
Run Code Online (Sandbox Code Playgroud)
我认为,因为数组声明的右侧是new Type2[2]数组将包含该类型的引用变量Type2.如果这是真的,那么第一个错误是有意义的,因为我不能有一个引用超类型的子类型.
但是,为什么第二个错误在那之后出现两行?method2()Type2 不知道,所以该方法是由引用变量知道的?它似乎是因为Type1不知道method2,所以这是否意味着数组由类型的引用变量组成Type1?如果这是真的,为什么第一个错误发生,因为它不再是指超类型的子类型?
另外,为什么第一个错误是运行时错误而另一个错误是语法错误?
请注意我只是在我的第二个编程课程,所以我的术语可能有点偏.
编辑:问题在这里并没有回答我的问题,因为它没有回答为什么像一个数组的元素x不能援引method2()即使的元素x的Type 2.我的问题因此而有所不同,因为我的问题也询问为什么第二个错误也会发生时出现第一个错误(为什么一个元素x不能引用该类型的对象Type1 …
我有一个名为Geometry的基类,其中存在一个子类Sphere:
public class Geometry
{
String shape_name;
String material;
public Geometry()
{
System.out.println("New geometric object created.");
}
}
Run Code Online (Sandbox Code Playgroud)
和子类:
public class Sphere extends Geometry
{
Vector3d center;
double radius;
public Sphere(Vector3d coords, double radius, String sphere_name, String material)
{
this.center = coords;
this.radius = radius;
super.shape_name = sphere_name;
super.material = material;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个包含所有Geometry对象的ArrayList,我想迭代它以检查是否正确读取了文本文件中的数据.到目前为止,这是我的迭代器方法:
public static void check()
{
Iterator<Geometry> e = objects.iterator();
while (e.hasNext())
{
Geometry g = (Geometry) e.next();
if (g instanceof …Run Code Online (Sandbox Code Playgroud) oop ×3
inheritance ×2
java ×2
aggregation ×1
arrays ×1
class ×1
composition ×1
polymorphism ×1
subclass ×1