在Java中,可以通过使用关键字super
来获取父类的属性。super
关键字表示对父类的引用,可以用于访问父类的成员变量和方法。
要获取父类的属性,可以按照以下步骤进行操作:
super
关键字来引用父类的属性,将其赋值给子类中的变量。以下是一个示例代码:
class Parent {
protected String parentProperty = "父类属性";
}
class Child extends Parent {
private String childProperty = "子类属性";
public void getParentProperty() {
String parentProperty = super.parentProperty; // 使用super关键字获取父类属性
System.out.println("父类属性值:" + parentProperty);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.getParentProperty();
}
}
输出结果为:
父类属性值:父类属性
在上述示例中,子类Child
继承了父类Parent
的属性parentProperty
。在子类中,通过使用super.parentProperty
来获取父类的属性值,并在getParentProperty()
方法中进行输出。
需要注意的是,父类的属性必须具有可访问性(即public
、protected
或默认访问性),否则子类无法直接访问父类的属性。
领取专属 10元无门槛券
手把手带您无忧上云