0%

【Java】抽象类作业


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package test1;

import java.util.Scanner;

public class Program{

public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println("Square:\nPlease enter the dim of Square:");
Square square=new Square(scanner.nextDouble());//实例化正方形对象
System.out.println("Area:"+square.callArea()+",Perimeter:"+square.callPerimeter());//打印数据
System.out.println("Rectangle:\nPlease enter the Width of Rectangle:");
double width=scanner.nextDouble();
System.out.println("Please enter the Length of Rectangle:");
double length=scanner.nextDouble();//实例化长方形对象
Rectangle rectangle=new Rectangle(length,width);
System.out.println("Area:"+rectangle.callArea()+",Perimeter:"+rectangle.callPerimeter());//打印数据
}

}

abstract class Shape//建立抽象类Shape
{
double dim;//一个边长度
public Shape(double dim)
{
this.dim=dim;
}//使用构造函数初始化这条边
public abstract double callArea();//建立抽象函数“求面积”
public abstract double callPerimeter();//建立抽象函数“求周长”
}

class Square extends Shape//建立正方形类
{
public Square(double dim)
{
super(dim);
}

public double callArea()
{
return dim*dim;
}//实现求面积方法

public double callPerimeter()
{
return dim*4;
}//实现求周长方法
}

class Rectangle extends Shape//建立矩形类
{
double dim2;//矩形有两条不一样长的边,故再建立一个字段存放第二条边的长度

public Rectangle(double length,double width)
{
super(length);//一条边由父类Shape的构造函数初始化
dim2=width;//另一条边在此初始化
}//将两条边初始化

public double callArea()
{
return dim*dim2;
}//实现求面积的方法

public double callPerimeter() {
return (dim+dim2)*2;
}//实现求周长的方法
}