首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >这个奇怪的继承循环是什么?

这个奇怪的继承循环是什么?
EN

Stack Overflow用户
提问于 2012-09-12 07:55:00
回答 2查看 1.5K关注 0票数 2

我使用多态数组创建了一个基本的继承程序。从父类中,这个数组循环通过,每个索引处的每个对象(从子类创建)执行父类的实例方法。

作为一个实验,我在子类中创建了一个对象,它的父类类型的构造函数,然后从那里执行父类实例方法。

因为我不知道的原因,这导致实例方法(从子类‘构造函数中执行)以父类’多态数组的长度执行次数(如果多态数组具有5元素,则子类的方法调用将执行5倍)。

以下是父级:

代码语言:javascript
复制
public class MyClass
{
    // instance variables
    protected String name;
    protected String numStrings;

    // constructor
    public MyClass(String name)
    {
        this.name = name;
    }

    // instance method
    public void getDescription()
    {
        System.out.println("The " + name + " has " + numStrings + " strings.");
    }

    // main method
    public static void main(String[] args)
    {
        MyClass[] instruments = new MyClass[2];

        instruments[0] = new Child("Ibanez bass guitar");
        instruments[1] = new Child("Warwick fretless bass guitar");

        for(int i = 0, len = instruments.length; i < len; i++)
        {
            instruments[i].getDescription();
        }
    } // end of main method
} // end of class MyClass

...here是儿童班:

代码语言:javascript
复制
public class Child extends MyClass
{
    // constructor
    public Child(String name)
    {
        super(name); // calling the parent-class' constructor
        super.numStrings = "four";

        MyClass obj = new MyClass("asdf");
        obj.getDescription();
    }
} // end of class Child

...and这里是输出:

代码语言:javascript
复制
The asdf has null strings.
The asdf has null strings.
The Ibanez bass guitar has four strings.
The Warwick fretless bass guitar has four strings.
EN

Stack Overflow用户

回答已采纳

发布于 2012-09-12 07:57:53

有问题的是:

代码语言:javascript
复制
MyClass obj = new MyClass("asdf");

如果您只是简单地调用getDescription()而不是obj.getDescription(),那么应该没有问题。由于'MyClass‘扩展了’new MyClass("...")‘,超级构造函数调用用于初始化超类中的所有内容(假设您现在可以将其想象为隐式new MyClass("...")),因此不必显式实例化'MyClass’。

票数 3
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12383552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档