java接口——矩形的计算,学习后的想法

版权声明:你们可以用哦,哈哈哈哈 https://blog.csdn.net/qq_44084157/article/details/90754477

和圆的计算一样,先建一个Shape接口,并且在里面写入,和圆接口一样的代码,这里你也可以直接用圆的Shape,只需建立两个类,分别是Rectangle,TestRectangle。
1.Shape接口
package lesson001.jiekou;

public interface Shape {
double PI = 3.1415926;
double circumference(); //计算周长
double area(); //计算圆
}

2.Rectangle类里面,这里代码看似很多,其实只要写出g 就可出现 public double getWidth() {
return width;
}
其他也是如此。要注意的是后面的返回部分要改成相应计算的公式。c矩形c的公式,和s的公式。

package lesson001.jiekou;

public class Rectangle implements Shape {
private double width;
private double heigth;

public double getWidth() {
    return width;
}

public void setWidth(double width) {

    this.width = width;
}

public double getHeigth() {
    return heigth;
}

public void setHeigth(double heigth) {

    this.heigth = heigth;
}

@Override
public double circumference() {
    return (width + heigth) * 2;
}

@Override
public double area() {
    return  width * heigth;
}

}

3。TestRectangle类,此时新建的类里面新定义的a,b 要相应的赋给width,heigth。
package lesson001.jiekou;

import lesson001.jiekou.Rectangle;

import java.util.Scanner;
public class TestRectangle {
public static void main(String[] args) {

    //声明部分
    double a,b,c,s;
    Scanner sc = new Scanner(System.in);
    Rectangle rectangle = new Rectangle();


   System.out.print("a= ");
   a =sc.nextDouble();
   System.out.print("b= ");
   b= sc.nextDouble();

    rectangle.setWidth(a);
    rectangle.setHeigth(b);


    c = rectangle.circumference();
    s =rectangle.area();

    System.out.println("c= " + c);
    System.out.println("s = " + s);

}

}

这次学习得内容不是很难,多加练习就可以记住,理解。
还有就是老师讲的太快,但是还好老师把笔记给我们看,不然什么都不知道

扫描二维码关注公众号,回复: 6639147 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_44084157/article/details/90754477