继承:从子类访问基类字段 [英] Inheritance: Access to base class fields from a subclass

查看:117
本文介绍了继承:从子类访问基类字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子类对象如何引用超类?例如:

How sub class objects can reference the super class? For example:

public class ParentClass {

    public ParentClass() {}     // No-arg constructor.

    protected String strField;
    private int intField;
    private byte byteField;
} 


public class ChildClass extends ParentClass{

    // It should have the parent fields.
}

此处 ChildClass 调用构造函数,创建一个 ParentClass 类型的对象,对吗?

Here when the ChildClass constructor is called, an object of type ParentClass is created, right?

ChildClass继承 strField ,因此它( ChildClass 对象)应该有权访问 ParentClass 某种方式的对象,但是如何?

ChildClass inherits strField from the ParentClass object, so it (ChildClass object) should have access to ParentClass object somehow, but how?

推荐答案

当你做 ChildClass childClassInstance = new ChildClass()仅创建一个新对象。

When you do ChildClass childClassInstance = new ChildClass() only one new object is created.

您可以将ChildClass视为由以下内容定义的对象:

You can see the ChildClass as an object defined by:


  • 字段来自来自ParentClass的ChildClass +字段。

因此字段 strField 是ChildClass的一部分,可以通过 childClassInstance.strField

So the field strField is part of ChildClass and can be accessed through childClassInstance.strField

所以你假设

ChildClass构造函数被称为ParentClass类型的对象被创建

ChildClass constructor is called an object of type ParentClass is created

不完全正确。创建的childClass实例也是一个ParentClass实例,它是同一个对象。

is not exactly right. The created childClass instance is ALSO a ParentClass instance, and it is the same object.

这篇关于继承:从子类访问基类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆