【问题标题】:In inheritance, when an object is created for subclass, is an object also created for its superclass?在继承中,当为子类创建对象时,是否也为其超类创建了对象?
【发布时间】:2014-03-21 10:30:01
【问题描述】:
  1. 在继承中,为子类创建对象时,是否也为其超类创建对象?
    我发现上述问题的答案是肯定的,它是创建的。我对吗?

  2. 基于正确的假设,我解决了这个问题,我发现答案是 4。 我说的对吗?

  3. long 是原始类型还是包装类?

问题:到达最后一个大括号时,有多少对象符合垃圾回收条件?

interface Animal {
   void makeNoise();
 }

class Horse implements Animal {
Long weight = 1200L;//here is Long a primitive variable or a wrapper class??
                    //If it is a wrapper class object, I think the answer to the   
                    // question would be 6  
public void makeNoise() {
System.out.println("whinny");
}
}

public class Icelandic extends Horse {

public void makeNoise() {
System.out.println("vinny");
}

public static void main(String[] args) {
Icelandic i1 = new Icelandic();
Icelandic i2 = new Icelandic();
Icelandic i3 = new Icelandic();

i3 = i1; i1 = i2; i2 = null; i3 = i1;
}
}

【问题讨论】:

  • 第一个问题,看this

标签: java inheritance garbage-collection wrapper


【解决方案1】:

在继承中,当为子类创建对象时,是一个对象 也为其超类创建?我找到了上面的答案 问题是肯定的,它是被创造出来的。我说的对吗?

不,当您创建子类对象时,它不会创建超类对象。通过继承超类,子类对象将具有超类功能主义者。创建子类对象时只会创建一个对象

long 是原始类型还是包装类??

long 是原始数据类型,Long 是对应的 Wrapper 类。

问题:到达最后一个大括号时,有多少对象符合条件 垃圾回收?

是的,将有 6 个对象,包括 3 个Long 对象

【讨论】:

  • 但它可以访问它的超类成员,因此它们必须存在,因此我认为创建了一个对象。如果没有,它如何访问它们?如果我错了,请纠正我?
  • 我现在明白了。最后一个,所以子类对象本身具有自身和超类的所有功能。那么子类对象的大小应该大于超类吗?因为它也包含超类。是这样吗?
  • @nikhil : 是的,当然,如果子类有更多的字段,子类对象会有更多的内存消耗
  • 谢谢@Kugathasan Abimaran。你已经清除了我的疑虑。非常感谢!
【解决方案2】:
  1. 它创建了一个对象,该对象既位于创建它的特定类中,也位于任何/所有超类中。就像 Fido 既是狗、哺乳动物又是动物一样。
  2. Lo​​ng 是一个包装器; long 是一个原语(注意第一个字母的大小写)。
  3. 您已经创建了 3 个冰岛人,每个人都有一个 Long: 6 个对象。由于您已结束该计划,我希望所有 6 人都有资格领取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2016-03-24
    • 2014-11-29
    • 2010-10-04
    相关资源
    最近更新 更多