Java 继承:从子类访问基类字段
子类对象如何引用超类?例如:Java 继承:从子类访问基类字段,java,oop,inheritance,Java,Oop,Inheritance,子类对象如何引用超类?例如: public class ParentClass { public ParentClass() {} // No-arg constructor. protected String strField; private int intField; private byte byteField; } public class ChildClass extends ParentClass{ // It shoul
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从父类对象继承
strField
,因此它(ChildClass
对象)应该以某种方式访问ParentClass
对象,但是如何访问呢?您可以访问strField
,就像它在ChildClass
中声明一样。为避免混淆,您可以添加一个super.strField
表示您正在访问父类中的字段。子类的实例没有ParentClass
对象,它是ParentClass
对象。作为子类,它可以访问其父类中的公共和受保护的属性/方法。因此这里的ChildClass
可以访问strField
,但不能访问intField
和byteField
,因为它们是私有的
您可以在不使用任何特定语法的情况下使用它。执行此操作时,只会创建一个新对象 您可以将
ChildClass
视为以下定义的对象:
- 来自
+来自ChildClass
的字段李>ParentClass
strField
是ChildClass的一部分,可以通过childClassInstance.strField
那么你的假设是
调用ChildClass
构造函数时,将创建类型为ParentClass
的对象
这并不完全正确。创建的
子类
实例也是一个父类
实例,它是同一个对象。是的,您可以从子类
访问strField
,而无需执行任何特殊操作(但是请注意,将只创建一个实例。子实例将从父实例继承所有属性和方法)
这里,当ChildClass构造函数被称为类型为
父类被创建了,对吗
否!调用了ChildClass构造函数>>调用了父类构造函数
并且不创建ParentClass的对象,只在ChildClass中继承父类的可访问字段
子类从父类对象继承strField,因此
(子类对象)应该以某种方式访问父类对象,
但是怎么做呢
不,这只是重用ParentClass的模板创建新的子类,只关注非参数构造函数和编译器的参与,而调用派生类(
ChildClass
)的默认构造函数(非参数构造函数),基类(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
这是一个很糟糕的标题。考虑在这里加上一些上下文。我同意,(-)现在更好了。