regin
2015-03-10 23:32
分了四个类class,用于保证内部继承属性的Sharp,矩形(Rectangle),圆(Circle)和调试用(initial);
Sharp:
package com.test2; public abstract class Sharp { public abstract void length(); public abstract void aera(); }
没什么说的就是个模板;
Circle:
package com.test2; public class Circle extends Sharp { public final double pi = 3.1415926; public double r; public void getR(double r){ this.r=r; } @Override public void length() { // TODO Auto-generated method stub double length = 2*pi*r; System.out.println("the Circle's length is "+length); } @Override public void aera() { // TODO Auto-generated method stub double aera = pi*r*r; System.out.println("the Circle's aera is "+aera); } }
继承Sharp,用getR将R分开;
Rectangle:
package com.test2; public class Rectangle extends Sharp { public int Long; public int wide; public void getLong(int Long ,int wide){ this.Long = Long; this.wide= wide; } @Override public void length() { // TODO Auto-generated method stub int length = 2*(Long+wide); System.out.println("the Rentangle's length is "+length); } @Override public void aera() { // TODO Auto-generated method stub int aera = Long*wide; System.out.println("the Rentangle's area is "+aera); } }
用 getLong(int,int)获得长,宽;
initail:
package com.test2; import java.util.Scanner; public class Initail { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("enter 1 for Rectangle ,0 for Circle"); Scanner scan = new Scanner(System.in); int i =(int)scan.nextDouble(); switch(i){ case 0: System.out.println("please enter r of the Circle:"); Circle cir = new Circle(); cir.getR(scan.nextDouble()); cir.length(); cir.aera(); break; case 1: Rectangle rectan = new Rectangle(); System.out.println("please enter the long and wide of the Rectangle:"); rectan.getLong((int)scan.nextDouble(),(int)scan.nextDouble()); rectan.length(); rectan.aera(); } } }
常规输出,还可以把输出再放到一个方法里面,避免写两条
rectan.length();
rectan.aera();
我懒就省了...
运行结果:
初学者表示楼主这段代码很有用,非常感谢!
谢谢楼主答案。
可读性好差。
Java入门第二季 升级版
530559 学习 · 6091 问题
相似问题