陆星崖
2019-02-20 00:53
图形类
package com.chy3.practice;
public abstract class Shape {
public abstract String square(double a,double b);
public abstract String circumFerence(double a,double b);
}
矩形类
package com.chy3.practice;
import java.util.Scanner;
public class Rectangle extends Shape {
Scanner input = new Scanner(System.in);
public void cal(){
System.out.println("计算矩形周长和面积");
System.out.println("请输入两条边长");
double stre1 = input.nextDouble();
double stre2 = input.nextDouble();
System.out.println("周长为: "+circumFerence(stre1, stre2));
System.out.println("面积为: "+square(stre1, stre2));
}
@Override
public String square(double a,double b) {
// TODO Auto-generated method stub
double squ = a*b;
return "矩形面积为:"+squ;
}
@Override
public String circumFerence(double a,double b) {
// TODO Auto-generated method stub
double cif = (a+b)*2;
return "矩形周长为"+cif;
}
}
圆形类
package com.chy3.practice;
import java.lang.Math;
import java.util.Scanner;
public class Circle extends Shape {
Scanner input = new Scanner(System.in);
Double p = Math.PI;
public void cal(){
System.out.println("计算圆形的周长和面积");
System.out.println("请输入半径和直径");
double r = input.nextDouble();
double d = input.nextDouble();
System.out.println("周长为: "+circumFerence(r, d));
System.out.println("面积为: "+square(r, d));
}
@Override
public String square(double a,double b) {
// TODO Auto-generated method stub
double squ = p*a*a;
return "圆的面积为"+squ;
}
@Override
public String circumFerence(double a,double b) {
// TODO Auto-generated method stub
double cif = 2*p*b;
return "圆的周长为"+cif;
}
}
实现类
package com.chy3.practice;
public class Initial {
public static void main(String[] args){
System.out.println("计算开始:");
Rectangle rec = new Rectangle();
rec.cal();
Circle cir = new Circle();
cir.cal();
}
}
可以加,圆的直径输入如果不是半径的2倍,那么输入错误,否则执行
我运行了你的代码,但是如果按老师讲的,用抽象类定义引用变量,指向子类对象为什么不行呢,代码和你的一样,只是测试类有点不同
你才是大神呀!
很优秀
没有了,已经很好了!!
Java入门第二季 升级版
530652 学习 · 6091 问题
相似问题
回答 3
回答 1