应用数学学院信息与计算科学专业 2 班学号3111008162
姓名许庆平教师评定_________________
实验题目继承与接口
一、实验目的与要求
实验目的:
1、掌握类的继承关系。
2、掌握接口的定义与使用。
实验要求:
按下列要求编写Java程序:
1、定义接口Printx,其中包括一个方法printMyWay(),这个方法没有形参,返回值为空。
2、编写矩形类,矩形类要求实现Printx接口,有求面积、求周长的方法,printMyWay()方法要能显示矩形的边长、面积和周长。
3、编写正方形类作为矩形类的子类,正方形类继承了矩形类求面积和周长的方法,新增加求对角线长的方法,重写printMyWay()方法,要求该方法能显示正方形的边长、面积、周长和对角线长。
二、实验方案
先按要求定义接口Printx,再创建一个矩形类Rectangle,有成员变量length 和width,area()求面积,circle()求周长,用PrintMyWay()显示。
然后定义正方形类,继承Rectangle类,定义求对角线长的函数duijiaoxian()。
面积和周长用父类中的area()和circle()实现。
用PrintMyWay()显示。
最后在主类中实现这两个类。
三、代码如下
interface Printx
{ void PrintMyWay();}
class Rectangle implements Printx
{
int length,width;
Rectangle(int x,int y){
length=x;
width=y;
}
int area(){
return length*width;
}
int circle(){
return 2*(length+width);
}
public void PrintMyWay(){
System.out.println("矩形的长为:"+length);
System.out.println("矩形的宽为:"+width);
System.out.println("矩形的面积为:"+area());
System.out.println("矩形的周长为:"+circle()); }
}
class Square extends Rectangle{
int lenth;
Square(int a){
super(a,a);
lenth=a;
}
double duijiaoxian(){
return Math.sqrt(2*length*length);
}
public void PrintMyWay(){
System.out.println("正方形的边长为:"
+lenth+" 正方形的面积为:"+
area()+" 正方形的周长为:"+circle()+" 正方形的对角线长为:"+duijiaoxian())
public class test {
public static void main(String[] args) {
Rectangle p;
p=new Rectangle(2,3);
p.PrintMyWay();
Square s;
s=new Square(4);
s.PrintMyWay();
}
}
四、实验结果和数据处理
三、结论
在类中定义的方法若要在主类中调用,就要定义为public方法,否则在主类中调用时会出错。
子类不能继承父类的构造函数,只能通过super调用父类的构造函数。
四、问题与讨论
问题:
在父类和子类中都定义的printMayWay()方法,为什么子类的对像只调了用子类printMayWay()方法,而没有调用父类的printMayWay()方法呢?
讨论:
因为子类的的方法会覆盖父类的方法,所以子类的对象只会调用子类的printMayWay()方法二不是调用父类的printMayWay()方法。