JAVA继承和多态实验报告

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验项目名称:继承和多态

(所属课程:Java语言程序设计)

院系:专业班级:姓名:

学号:实验地点:指导老师:

本实验项目成绩:教师签字:日期:

1.实验目的

(1)掌握类的继承机制。

(2)熟悉类中成员变量和方法的访问控制。

(3)熟悉方法或构造方法多态性。

2.实验内容

(1)模拟编写程序,理解类的继承、多态、继承和多态规则。

(2)独立编程,实现类的继承和多态。

3.实验作业

设计一个类Shape(图形)包含求面积和周长的area()方法和perimeter()方法以及设置颜色的方法SetColor(),并利用Java多态技术设计其子类Circle(圆形)类、Rectangle (矩形)类和Triangle(三角形)类,并分别实现相应的求面积和求周长的方法。每个类都要覆盖toString方法。

海伦公式:三角形的面积等于s(s-a)(s-b)(s-c)的开方,其中s=(a+b+c)/2

程序代码为:

Class包

package Class;

public class Shape {

private String color = "while";

public Shape(String color){

this.color = color;

}

public void setColor(String color){

this.color = color;

}

public String getColor(){

return color;

}

public double getArea(){

return 0;

}

public double getPerimeter(){

return 0;

}

public String toString(){

return"color:" + color;

}

}

package Class;

public class Circle extends Shape {

private double radius;

public Circle(String color,double radius) { super(color);

this.radius = radius;

}

public void setRadius(double radius){

this.radius = radius;

}

public double getRadius(){

return radius;

}

public double getCircleArea(){

return 3.14*radius*radius;

}

public double getCirclePerimeter(){

return 3.14*2*radius;

}

public String toString(){

return"The Area is:" + getCircleArea()

+ "\nThe Perimeter is:" + getCirclePerimeter();

}

}

package Class;

public class Rectangle extends Shape{

private double width;

private double height;

public Rectangle(String color,double width,double height) { super(color);

this.width = width;

this.height = height;

}

public void setWidth(double width){

this.width = width;

}

public double getWidth(){

return width;

}

public void setHeight(double height){

this.height = height;

}

public double getHeight(){

return height;

}

public double getRectangleArea(){

return width*height;

}

public double getRectanglePerimeter(){

return 2*(width + height);

}

public String toString(){

return"The Area is:" + getRectangleArea()

+ "\nThe Perimeter is:" + getRectanglePerimeter();

}

}

package Class;

public class Triangle extends Shape{

private double a;

private double b;

private double c;

private double s;

public Triangle(String color,double a,double b,double c, double s){ super(color);

this.a = a;

this.b = b;

this.c = c;

this.s = s;

}

public void setA(double a){

this.a = a;

}

public double getA(){

return a;

}

public void setB(double b){

this.b = b;

}

public double getB(){

return b;

}

public void setC(double c){

this.c = c;

}

相关文档
最新文档