Java中父类的属性值全部赋给子类的方法
时间: 2023-05-12 07:07:40 浏览: 867
可以使用 super 关键字来调用父类的属性和方法,然后在子类中进行赋值操作。具体实现可以参考以下代码:
public class ParentClass {
protected int parentAttr;
public ParentClass(int parentAttr) {
this.parentAttr = parentAttr;
}
}
public class ChildClass extends ParentClass {
private int childAttr;
public ChildClass(int parentAttr, int childAttr) {
super(parentAttr);
this.childAttr = childAttr;
}
public void assignParentAttrToChild() {
this.childAttr = super.parentAttr;
}
}
在这个例子中,ChildClass 继承了 ParentClass,并且在构造函数中使用 super 关键字调用了父类的构造函数。然后在 assignParentAttrToChild 方法中,使用 super 关键字调用了父类的 parentAttr 属性,并将其赋值给了子类的 childAttr 属性。
相关问题
java把子类属性赋值给父类属性
在Java中,您可以通过使用super关键字来访问父类的属性和方法。如果您想在子类中将子类的属性值赋给父类的属性,可以在子类的构造函数中使用super关键字来调用父类的构造函数,并将子类的属性作为参数传递给父类构造函数。例如:
```
public class Parent {
protected int parentProperty;
public Parent(int parentProperty) {
this.parentProperty = parentProperty;
}
}
public class Child extends Parent {
private int childProperty;
public Child(int parentProperty, int childProperty) {
super(parentProperty);
this.childProperty = childProperty;
}
public void setParentProperty(int parentProperty) {
super.parentProperty = parentProperty;
}
}
```
在这个例子中,子类Child继承了父类Parent,并在其构造函数中调用了父类的构造函数,将parentProperty传递给了父类。同时,子类Child也有自己的属性childProperty。如果您想将子类的属性值赋给父类的属性,可以使用setParentProperty方法来访问父类的parentProperty属性,并将子类的属性值赋给它。在这个例子中,我们使用了super关键字来访问父类的属性。
java 继承中如何通过子类改变父类中属性的值
在Java中,可以通过子类继承父类的属性,并且在子类中使用关键字super来访问父类的属性。如果要修改父类的属性值,可以在子类中定义同名的属性,并且使用super关键字调用父类的构造函数来初始化父类的属性。例如:
```
public class ParentClass {
protected int num = 10;
}
public class ChildClass extends ParentClass {
public ChildClass() {
super();
num = 20;
}
}
```
在上面的例子中,子类ChildClass继承了父类ParentClass的属性num,并且在子类中重新定义了同名的属性。在子类的构造函数中,使用super关键字调用父类的构造函数,并将num的值赋为20,从而改变了父类中属性的值。