Vadu1337
Vadu1337

Reputation: 1

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. You need to create two Shape subclasses, Square and Circle, which initialize the width attribute using their constructor, and define their area() methods. 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). The code in main creates two objects with the given user input and calls the area() methods.

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();
    }
}


Upvotes: 0

Views: 456

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191844

You've written a function within a constructor. 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. At least, probably shouldn't be ; you'll want to change abstract void area(); in the abstract 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.

Implementing Circle I'll leave up to you.

More info -

Upvotes: 1

Related Questions