1. 定义一个点(Point)类,它包含横坐标x和纵坐标y两个属性,再给Point定义两个构造方法和一个打印点坐标的方法(Show())。 2. 定义一个圆(Circle)类,它继承Point类(它是一个点,圆心(Center)),除此之外,还有属性半径(Radius),再给圆定义2个构造方法、一个打印圆的面积的方法(PrintArea())和一个打印圆中心、半径的方法(Show())。
3. 在记事本编辑如下源程序: class Point{
protected int x; protected int y; Point(){ SetXY(0,0); }
Point(int a,int b) { SetXY(a,b); }
public int GetX() { return x; }
public int GetY() { return y; }
public void SetXY(int a, int b) { x =a; y =b; }
public void Show() { if(this instanceof Circle) System.out.println(\中心: \ else System.out.println(\点: \ } }
class Circle extends Point{ final double PI =3.1415926; protected int Radius; Circle() { Radius =5; }
Circle(Point Center, int Radius) { super(Center.GetX(),Center.GetY()); this.Radius =Radius;
}
public void PrintArea() { double area =PI*Radius*Radius; System.out.println(\ System.out.println(\面积:\ System.out.println(\ }
public void Show() { super.Show(); System.out.println(\半径: \ } }
public class Ex6 {
public static void main(String[] args) { Point center =new Point(2,2); center.Show(); int radius =3; Circle cir1 =new Circle(); cir1.Show(); cir1.PrintArea(); Circle cir4 =new Circle(center,radius); cir4.Show(); cir4.PrintArea(); } }
4. 保存程序Ex6.java,编译运行程序,观察并分析程序的运行结果。
5. 去掉语句“super.Show();”,再看看运行结果。理解程序中多太性的运用。
6. 在语句“SetXY(0,0);”和语句“SetXY(a,b);”添加一条语句“System.out.println(\构造点(\\”,在语句“Radius =5;”和语句“this.Radius =Radius;”添加一条语句“System.out.println(\构造圆(半径: \”,重新编译运行程序,观察并理解所得到的结果,从而理解在继承关系中构造方法的调用过程。
实验四、类的继承
[实验目的]
理解继承的含义、掌握方法的覆盖及super关键字的用法、理解继承层次中类的构造方法的定义方