0

Help me Overriding in Java

please help my confuse hehehehe: want to create like this: Sample Input: 7 2 Sample Output: 49 12.566370614359172 The area of the square is 5*5=25, while the area of the circle is PI*2*2=12.566370614359172 the program like this: import java.util.Scanner; abstract class Shape { int width; abstract void area(); } //your code goes here public class Square extends Shape { public void area() { System.out.println(width*width); } } public class Circle extends Shape { public void area() { System.out.println( Math.PI*width*width); } } 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(); } } but the overriding code are always false.

5th Aug 2021, 7:08 AM
Choi_142
Choi_142 - avatar
7 Answers
0
how about this code, because when run also result error: public class Square extends Shape { public void area() { System.out.println(width*width); } } public class Circle extends Shape { public void area() { System.out.println( Math.PI*width*width); } }
5th Aug 2021, 7:30 AM
Choi_142
Choi_142 - avatar
0
Use this.width so that it will be going to call the current object
5th Aug 2021, 7:32 AM
Atul [Inactive]
0
And make constructors too for it
5th Aug 2021, 7:32 AM
Atul [Inactive]
0
thankyou sir, but the program still error: /usercode/Program.java:12: error: constructor Square in class Square cannot be applied to given types; Square a = new Square(x); ^ required: no arguments found: int reason: actual and formal argument lists differ in length /usercode/Program.java:13: error: constructor Circle in class Circle cannot be applied to given types; Circle b = new Circle(y); ^ required: no arguments found: int reason: actual and formal argument lists differ in length 2 errors
5th Aug 2021, 7:34 AM
Choi_142
Choi_142 - avatar
0
Make Circle and Square constructors
5th Aug 2021, 7:54 AM
Atul [Inactive]
0
If you have done that then take the argument of width and write this.width=width
5th Aug 2021, 7:55 AM
Atul [Inactive]
0
Thankyou very much all Master, the case has solved by using this code: ``` package com.inheritence; import java.util.Scanner; abstract class Shape { int width; abstract void area(); } class Square extends Shape { Square(int width) { super.width = width; System.out.println( width * width); } @Override void area() { int luas = width*width; } } class Circle extends Shape { Circle(int width) { super.width = width; System.out.println( Math.PI*width * width); } @Override void area() { double luas = Math.PI*width*width; } } public class Main { public static void main(String[] args) { // write your code here 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(); } } ```
8th Aug 2021, 9:42 AM
Choi_142
Choi_142 - avatar