+ 1

Third test is error. I don't know why. Lesson 56. Project figures.

import java.util.Scanner; abstract class Shape { private int width; abstract void area(); public int getWidth(){ return width;} Shape(int x){ width=x; } } class Square extends Shape{ Square(int x){ super(x); } void area(){ System.out.println((int)Math.pow(getWidth(),2)); } } //введите код сюда class Circle extends Shape{ Circle(int x){ super(x); } void area(){ System.out.println(Math.PI*Math.pow(getWidth(),2)); } } 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(); } }

20th Feb 2021, 11:01 AM
Владимир
Владимир - avatar
5 Antworten
+ 2
1. You weren't supposed to change the abstract class Shape. 2. The class Shape is abstract. This means that you don't define the body of the methods or set values for the properties. The methods within it should likewise be abstract. It is meant to just be an outline and it's members should be defined in its child class(es). abstract class Shape { int width; abstract void area(); } 3. Now, since the Square and Circle classes extend Shape, width is inherited. You can the just use; this.width = x; // where x is the parameter for the constructor. 4. Then use this.width in your area() methods in place of your getWidth(). You don't really need to use Math.pow() either. this.width * this.width will suffice.
20th Feb 2021, 12:24 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
It's most likely a precision issue due to the use of Math.pow(). Change to use Math.PI*width*width and your code works fine.
20th Feb 2021, 3:23 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Thank you. P. S. Sorry for my English
20th Feb 2021, 3:30 PM
Владимир
Владимир - avatar
+ 1
Владимир No worries, you're welcome
20th Feb 2021, 4:09 PM
ChaoticDawg
ChaoticDawg - avatar
0
If class is abstract, not mean that we can't write getter in its. Ok, why this code don't work?? The third test fails, the rest are correct import java.util.Scanner; abstract class Shape { int width; abstract void area(); } //введите код сюда class Square extends Shape{ Square(int x){ width=x; } void area(){ System.out.println((int)Math.pow(width,2)); } } //введите код сюда class Circle extends Shape{ Circle(int x){ width=x; } void area(){ System.out.println(Math.PI*Math.pow(width,2)); } } 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(); } }
20th Feb 2021, 3:04 PM
Владимир
Владимир - avatar