2013-09-28 33 views
1

我想了解Java中的面向对象编程,我有这个问题。如何使用父类中的字段实例化对象?

比方说,我有AA父类是这样的:

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; 
    } 


} 

如何让我的孩子上课,这样我可以构建,也就是说,一个长方形的起始位置,并在初始颜色主要方法?我是否在Rectangle类中创建构造函数?我不能因为位置和颜色是私人领域。我是否创建位置和颜色的存取方法,并在实例化后设置位置和颜色?我想,但有没有办法做到这一点,没有访问者?

public class Rectangle extends Shape { 
    public Rectangle(int initialLocation, Color initialColor) { 
     super(initialLocation, initialColor); 
    } 

} 

我只是不能笼罩这个基本概念。任何帮助?

+1

您可以重复使用您的父类的构造函数与“超(...)'调用。或使用setter。 –

+0

为什么地球上会有'矩形'延伸'车辆'? –

+0

@RohitJain车?哪里? – Dukeling

回答

4

重用构造

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解释了它的使用。

+0

我根据你的建议编辑了我的代码。谢谢! –

+1

@Giga你还有问题吗? –

+0

是的,如果我有更长的继承层次结构。例如,Shape - > MovingShape - > Rectangle。我必须以同样的方式为MovingShape类创建构造函数。正确? –

1

如果您想扩展变量,您可以将其修饰符更改为protected,因此它可以被继承,否则private就像它们不存在的子类。

1

但是,您可以将实例变量定义为protected,但这违背了面向对象的封装原则。我会为类Shape的每个实例变量使用getter和setter。此外,如果在Shape中创建构造函数,则可以调用Rectangle中的超级构造函数来设置Rectangle中的位置和颜色。

public class Rectangle extends Shape { 
    public Rectangle(int location, Color color) { 
     super(location, color); 
    } 
} 

只要你在外形下面的构造:

public class Shape { 
    // location and color define. 

    public Shape(int location, Color color) { 
     this.location = location; 
     this.color = color; 
    } 
    // getters and setters which are public for location and color 
} 
0

在基类私有成员只能由子类访问是毫无意义的! 如果你想阅读它们,你至少需要一个公共的或受保护的吸气剂。 如果你想写他们,你至少需要一个公共或受保护的setter和/或一个构造函数来初始化它们。

相关问题