书上的一段代码如下:class TwoDShape
{
private double width;
private double height;
double getWidth() {return width;}
double getHeight() {return height;}
}class Triangle extends TwoDShape
{
double area()
{
return getWidth() * getHeight() / 2;
}
}
书上用private来修饰父类的域,然后子类中通过调用父类的public方法(accessor)来间接使用父类的域,这样感觉很奇怪啊,为什么不直接把父类中的域用protected来修饰,然后在子类中直接调用呢?代码如下:class TwoDShape
{
protected double width;
protected double height;
double getWidth() {return width;}
double getHeight() {return height;}
}class Triangle extends TwoDShape
{
double area()
{
return width * height / 2;
}
}
书上既然使用private,是不是有什么特别的好处呢?或者说,从设计模式上来考虑,使用private更好么?
{
private double width;
private double height;
double getWidth() {return width;}
double getHeight() {return height;}
}class Triangle extends TwoDShape
{
double area()
{
return getWidth() * getHeight() / 2;
}
}
书上用private来修饰父类的域,然后子类中通过调用父类的public方法(accessor)来间接使用父类的域,这样感觉很奇怪啊,为什么不直接把父类中的域用protected来修饰,然后在子类中直接调用呢?代码如下:class TwoDShape
{
protected double width;
protected double height;
double getWidth() {return width;}
double getHeight() {return height;}
}class Triangle extends TwoDShape
{
double area()
{
return width * height / 2;
}
}
书上既然使用private,是不是有什么特别的好处呢?或者说,从设计模式上来考虑,使用private更好么?
让其他类能够访问到自己的域是很危险的,可以随意的进行修改。
改用getxxx(),只是可以读,不能写。
java中能不用继承最好不要用继承,你那个类的方法在一般程序是不会用的,
对于运算,可以考虑使用组合设计模式。
没事多看Thinking in java
private 根本无法让子类继承后得到,
继承其实是针对实例来说,继承,为什么要去继承父类,无非就是想不劳而获的得到一些资源,
其实java里实现也是这样的,继承以后会先实例化父类,而后子类就可以有父类的资源。其实java很多父类里源码很多都是protected修饰的。 private double width;
private double height;显然是设计上不正确,因为底和高三角形也有!