+ 1

Java Puzzle

Need help discussing approach to this

13th Aug 2022, 11:41 AM
Linux Penguin
6 Answers
+ 1
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. Sample Input: 5 2 Sample Output: 25 12.566370614359172 The area of the square is 5*5=25, while the area of the circle is PI*2*2=12.566370614359172
13th Aug 2022, 11:41 AM
Linux Penguin
+ 1
import java.util.Scanner; abstract class Shape { int width; abstract void area(); } //your code goes here 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(); } }
13th Aug 2022, 11:42 AM
Linux Penguin
+ 1
What you need is to learn about inheritence. And define Circle, Square classes which will have method area() which print the area of shape. Remaining code is given predifinedly.
13th Aug 2022, 11:50 AM
Jayakrishna 🇼🇳
+ 1
Ok so i extend the shape class, and use a constant variable area
13th Aug 2022, 11:52 AM
Linux Penguin
+ 1
ahh use super. method thanks
13th Aug 2022, 1:31 PM
Linux Penguin
0
Extend shape class and use super class variable width in overriding area() method to display area value..
13th Aug 2022, 1:14 PM
Jayakrishna 🇼🇳