ART原艺美学
2017-03-08 16:56
父类 package imooc02; public abstract class Shape { public abstract void Perimeter(); public abstract void Area(); } 子类01 package imooc02; public class Rectangle extends Shape { @Override public void Perimeter() { // TODO Auto-generated method stub double a; double b; double c; double c= (a+b)*(a+b); System.out.println("长方形的周长为"+c); } @Override public void Area(){ // TODO Auto-generated method stub double a ; double b; double s; double s= a*b; System.out.println("长方形的的面积为"+s); } } 子类02 package imooc02; public class Circle extends Shape { @Override public void Perimeter(){ // TODO Auto-generated method stub double π; double d; private double c ; private double c= π*d; System.out.println("圆的周长是:"+c); } @Override public void Area(){ // TODO Auto-generated method stub double π; double d; double s; double s= π*((d/2)*(d/2)); System.out.println("圆的面积是:"+s); } } 测试类 package imooc02; public class Test { public static void main(String[] args) { Shape a1=new Rectangle(); a1.Perimeter(); a1.Area(); Shape a2=new Circle(); a2.Perimeter(); a2.Area(); } }
将double π 定义为常量 final PI=3.14;试试
既然一个类里面两个方法的变量都一样的话,可以直接拿出来啊,在类里定义写一遍就好了。
父类 package imooc02; public abstract class Shape { public abstract void Perimeter(); public abstract void Area(); } 子类 package imooc02; public class Rectangle extends Shape { @Override public void Perimeter() { // TODO Auto-generated method stub double a=10.0; double b=10.0; double c; c= (a+b)*2; System.out.println("长方形的周长为"+c); } @Override public void Area(){ // TODO Auto-generated method stub double a=10.0 ; double b=10.0; double s; s= a*b; System.out.println("长方形的的面积为"+s); } } 子类02 package imooc02; public class Circle extends Shape { @Override public void Perimeter(){ // TODO Auto-generated method stub final double PI=3.14; double d=9.0; double c ; c= PI*d; System.out.println("圆的周长是:"+c); } @Override public void Area(){ // TODO Auto-generated method stub final double PI=3.14;; double d=9.0; double s; s= PI*(d/2); System.out.println("圆的面积是:"+s); } } 测试类 package imooc02; public class Test { public static void main(String[] args) { Shape a1=new Rectangle(); a1.Perimeter(); a1.Area(); Shape a2=new Circle(); a2.Perimeter(); a2.Area(); } } 长方形的周长为40.0 长方形的的面积为100.0 圆的周长是:28.26 圆的面积是:14.13
Java入门第二季 升级版
530655 学习 · 6091 问题
相似问题