首页 > 解决方案 > 在Java中的抽象类中获取运行时输入

问题描述

问题陈述是“开发一个 Java 程序来创建一个名为的抽象类Shape,其中包含两个整数和一个名为的空方法printArea()。提供三个名为 的类RectangleTriangle并且Circle每个类都扩展类 Shape。每个类仅包含printArea()打印给定形状区域的方法。”

在这个程序中,我想Shape从用户(运行时)而不是编译时获取抽象类包含的两个整数值。

这是我的代码

abstract class Shape

{   

    abstract void Printarea();

    int a=10,b=2;;

}

class Rectangle extends Shape

{

    void Printarea()

    {       

       System.out.println("area of rectangle is "+(a*b));

    }

}     

class Triangle extends Shape

{

    void Printarea()

    {       

        System.out.println("area of triangle is "+(0.5*a*b));

    }

}   



class Circle extends Shape

{       

    void Printarea()

   {       

        System.out.println("area of circle is "+(3.14*a*a));

   }  

}   

class Main

{

    public static void main(String []args)       

    {     

       Shape=b;

       b=new Circle();      

       b.Printarea();

       b=new Rectangle();

       b.Printarea();    

       b=new Triangle();

       b.Printarea();

   }

}

标签: javaoopabstract-class

解决方案


一些快速的代码,但按预期工作,会给你的想法:

import java.util.Scanner;

abstract class Shape {

    int a = 10, b = 2;

    Shape(int a, int b){
        this.a=a;
        this.b=b;
    }

    abstract void Printarea();

}

class Rectangle extends Shape {

    Rectangle(int a, int b) {
        super(a, b);
    }

    void Printarea() {
        System.out.println("area of rectangle is " + (a * b));
    }

}

class Triangle extends Shape {

    Triangle(int a, int b) {
        super(a, b);
    }

    void Printarea(){
        System.out.println("area of triangle is " + (0.5 * a * b));
    }

}

class Circle extends Shape {

    Circle(int a, int b) {
        super(a, b);
    }

    void Printarea() {
        System.out.println("area of circle is " + (3.14 * a * a));
    }

}

class Z {

    public static void main(String[] args){

        Shape shape=null;

        String input;
        int width, height;

        while (true) {

            Scanner scanner = new Scanner(System.in);

            System.out.println("which shape? circle/rectangle/triangle (write any other thing for quitting): ");
            input = scanner.nextLine();

            if(!"circle".equalsIgnoreCase(input) && !"rectangle".equalsIgnoreCase(input) && !"triangle".equalsIgnoreCase(input) ){
                System.exit(0);
            }

            System.out.println("height: ");
            height  = scanner.nextInt();

            System.out.println("width: ");
            width = scanner.nextInt();

            if("circle".equalsIgnoreCase(input)){
                shape=new Circle(width, height);
            }
            else if("rectangle".equalsIgnoreCase(input)){
                shape=new Rectangle(width, height);
            }
            else{ // == triangle
                shape=new Triangle(width, height);
            }

            shape.Printarea();

        }

    }

}

推荐阅读