0
I can't find error in my Java Shapes Project .Help
import java.util.Scanner; abstract class Shape { int width; abstract void area(); } public class Square extends Shape{ Square(int width){ @Override void area() { System.out.println(width*width); } } } public class Circle extends Shape{ Circle(int width){ @Override 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(); } }
5 Antworten
+ 4
You are adding method inside a constructor method which is invalid.
Complete constructor by assinging passed parameter value into width variable and next, after it add area() method..
+ 3
Rez Smith In your code , example for Square:
Square ( int w) {
this.width = w;
}
Here, passing to w, then assign it width of super class Shape variable which is value you are using to find area..
Similar do in Circle.
+ 1
import java.util.Scanner;
abstract class Shape {
int width;
abstract void area();
}
public class Square extends Shape{
Square(int width){}
@Override
void area() {
System.out.println(width*width);
}
}
public class Circle extends Shape{
Circle(int width){}
@Override
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();
}
}
+ 1
I don't know how to use passed parameter .can anyone show answer code
+ 1
Jayakrishna🇮🇳 Thanks