zoukankan      html  css  js  c++  java
  • 【java】 向上转型的运用

    应用 :求面积

    1,抽象类  Geometry .

    public abstract class Geometry {
        
        public abstract double getArea();
        
    }

    2,矩形 Rect

    public class Rect extends Geometry{
        
        double a,b;
        
        Rect(double a,double b){
            this.a = a;
            this.b = b;
        }
        
        @Override
        public double getArea() {
            return a*b;
        }
        
    }

    3,圆形 Circle

    public class Circle extends Geometry{
        double r;
        
        public Circle(double r) {
            this.r = r;
        }
        
        @Override
        public double getArea() {
            // TODO Auto-generated method stub
            return 3.14*r*r;
        }
        
    }

    4,  数组存模 , 使用抽象方法 。  求面积和   (注入灵魂) 

    public class TotalArea {
        
        double area(Geometry ...p) {
        
            double sum = 0;
            
            for (int i = 0; i < p.length; i++) {
                
                sum += p[i].getArea();
                
            }
            
            return sum;    
        }
    
    }

    5 , 主类 Main

    public class Main {
        
        public static void main(String[] args) {
            
            TotalArea t = new TotalArea();
            
            double area = t.area(new Rect(2, 3),new Circle(5.2),new Circle(12));
            
            System.out.printf("面积和: 
    ",area);
            
        }
        
    }
  • 相关阅读:
    【bzoj1010】[HNOI2008]玩具装箱toy
    bzoj 3173
    bzoj 1179
    bzoj 2427
    bzoj 1051
    bzoj 1877
    bzoj 1066
    bzoj 2127
    bzoj 1412
    bzoj 3438
  • 原文地址:https://www.cnblogs.com/500m/p/14048459.html
Copyright © 2011-2022 走看看