简体   繁体   English

创建两个 Shape 子类

[英]create two Shape subclasses

You are working on a graphical app, which includes multiple different shapes.您正在开发一个图形应用程序,其中包含多种不同的形状。 The given code declares a base Shape class with an abstract area() method and a width attribute.给定的代码声明了一个基本形状 class,其中包含一个抽象的 area() 方法和一个 width 属性。 You need to create two Shape subclasses, Square and Circle, which initialize the width attribute using their constructor, and define their area() methods.您需要创建两个 Shape 子类,Square 和 Circle,它们使用构造函数初始化 width 属性,并定义它们的 area() 方法。 The area() for the Square class should output the area of the square (the square of the width), while for the Circle, it should output the area of the given circle (PI*width*width). Square class 的 area() 应该是 output 正方形的面积(宽度的平方),而对于 Circle,它应该是 output 给定圆的面积(PI * width * width)。 The code in main creates two objects with the given user input and calls the area() methods. main 中的代码使用给定的用户输入创建两个对象并调用 area() 方法。

I already started writing some code, but it doesn't work and I think I made more than just one mistake.我已经开始编写一些代码,但它不起作用,而且我认为我犯的错误不止一个。


import java.util.Scanner;

abstract class Shape {
    int width;
    abstract void area();
}
//your code goes here

class Square extends Shape {

    int width = x;
    
    Square() {

    int area(){
    area = x*x;
    }
}
}

class Circle extends Shape {
    
    int width = (double) y;

    Circle(){
    
    double area() {
    area = Math.PI*y*y;
    }
}
}

public class Program {
    public static void main(String[ ] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();
        
        Square a = new Square(x);
        Circle b = new Circle(y);
        a.area();
        b.area();
    }
}


You've written a function within a constructor.您已经在构造函数中编写了 function。 That's not valid, and you should be seeing a syntax error...那是无效的,您应该会看到语法错误...

I assume you also will want parameters to constructors as given in the main method, and you need to return from your area function since it isn't void.我假设您还需要 main 方法中给定的构造函数参数,并且您需要从您的区域 function return ,因为它不是空的。 At least, probably shouldn't be;至少,可能不应该是; you'll want to change abstract void area();你会想要改变abstract void area(); in the abstract class摘要 class

class Square extends Shape {
    
    public Square(int x) { 
        super.width = x;  // sets field of parent class 
    }

    @Overrides
    public double area(){
        return 1.0 * super.width * super.width;
    }
}

Then you want System.out.println (a.area()) in the main method.然后你想在 main 方法中使用System.out.println (a.area())

Implementing Circle I'll leave up to you.实施 Circle 我会留给你。

More info -更多信息 -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM