inheritance:从子类访问基类字段

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

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类型的对象,对吧?

ChildClass从ParentClass对象inheritancestrField ,因此它( ChildClass对象)应该以某种方式访问ParentClass对象,但是如何?

当您执行ChildClass childClassInstance = new ChildClass()只会创建一个新对象。

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

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

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

所以你的假设

调用ChildClass构造函数时,会创建一个ParentClass类型的对象

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

ChildClass的实例没有ParentClass对象,它 ParentClass对象。 作为子类,它可以访问其父类中的public和protected属性/方法。 所以这里ChildClass可以访问strField ,但不能访问intFieldbyteField因为它们是私有的。

您可以使用它而无需任何特定语法。

您可以像访问strField一样访问strField 。 为避免混淆,您可以添加super.strField这意味着您正在访问父类中的字段。

这里当调用ChildClass构造函数时,创建了一个ParentClass类型的对象,对吧?

没有! 调用ChildClass构造函数>>调用父类constr并创建ParentClass的No Object只是父类中的可访问字段在ChildClass中inheritance

ChildClass从ParentClass OBJECTinheritancestrField,因此它(ChildClass对象)应该以某种方式访问​​ParentClass对象,但是如何?

不,它只是重用ParentClass的模板来创建新的ChildClass

是的,您将能够从ChildClass访问strField ,而无需执行任何特殊操作(请注意,只会创建一个实例。该子级将inheritance父级的所有属性和方法)。

通过专注于非arg构造函数和编译器的参与业务,当调用派生类( ChildClass )的默认构造函数(非arg构造函数)时,通过以下机制创建基类( ParentClass )的子对象。编译器的帮助(在派生类中插入基类构造函数调用)并包装在派生类的对象中。

 class Parent{ String str = "i_am_parent"; int i = 1; Parent(){System.out.println("Parent()");} } class Child extends Parent{ String str = "i_am_child"; int i = 2; Child(){System.out.println("Child()");} void info(){ System.out.println("Child: [String:" + str + ", Int: " + i+ "]"); System.out.println("Parent: [String: ]" + super.str + ", Int: " + super.i + "]"); } String getParentString(){ return super.str;} int getParentInt(){ return super.i;} public static void main(String[] args){ Child child = new Child(); System.out.println("object && subojbect"); child.info(); System.out.println("subojbect read access"); System.out.println(child.getParentString()); System.out.println(child.getParentInt()); } } 

结果:

 Parent() Child() object && subojbect Child: [String:i_am_child, Int: 2] Parent: [String: ]i_am_parent, Int: 1] subojbect read access i_am_parent 1