在超类中将成员声明为protected,超类的子类可以继承超类的protected成员。
public class Point {
protected int x;
protected int y;
public Point(){}
public Point(int x,int y){
this.x=x;
this.y=y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
public String toString(){
return "["+x+","+y+"]";
}
}
public class Circle extends Point{
private double radius;
public Circle(){
}
public Circle(int x,int y,double r){
this.x=x;
this.y=y;
setRadius(r);
}
public void setRadius(double radius) {
this.radius=(radius<0.0?0.0:radius);
}
public double getRadius() {
return radius;
}
public double getDiameter(){
return 2*radius;
}
public double getArea(){
return Math.PI*radius*radius;
}
public String toString(){
return "Center=["+x+","+y+"];Radius= " +radius;
}
}
如果将超类的成员声明为private, 子类继承非private超类的方法(setY,setX,getX,getY),并能用这些方法来访问超类的private 成员。
代码将有所修改
public Circle(int xValue,int yValue,double r){
super(xValue,yValue);
setRadius(r);
}