我正在尝试了解 Java 中的面向对象编程,但我遇到了这个问题。
例如,我有一个这样的父类:
public class Shape {
private int location;
private Color color;
// methods such as getLocation() and getColor()
public Shape(int initialLocation, Color initialColor) {
location = initialLocation;
color = initialColor;
}
}
如何创建我的子类,以便我可以在 main 方法中构造一个具有初始位置和初始颜色的矩形?我是否在 Rectangle 类中创建构造函数?我不能,因为位置和颜色是私有(private)领域。我是否为位置和颜色创建访问器方法并在实例化后设置位置和颜色?我想,但是有没有办法在没有访问器的情况下做到这一点?
public class Rectangle extends Shape {
public Rectangle(int initialLocation, Color initialColor) {
super(initialLocation, initialColor);
}
}
我只是无法理解这个基本概念。有帮助吗?
最佳答案
重用构造函数
public class Shape {
private int location;
private Color color;
public Shape(int location, Color color) {
this.location = location;
this.color = color;
}
// methods such as getLocation() and getColor()
}
和
public class Rectangle extends Shape {
public Rectangle(int location, Color color /*, more */) {
super(location, color);
// more
}
}
这official tutorial解释其用途。
关于java - 如何用父类的字段实例化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19071491/