This is the code I wrote where base class is shape and there are 3 methods for the shape area using same keyword but different parameters, and in the main I have 1 class for each shape and which is derived from the shape class, but after running the main method I get a blank output with exit code.
package com.company;
import java.util.Scanner;
class Shape {
int b, h, s;
double r;
//triangle method
void area(int base, int height) {
int triArea = (base * height)/2;
System.out.println("Area of Triangle = " triArea);
}
//square method
void area(int side) {
int sqrArea = side * side;
System.out.println("Area of Square = " sqrArea);
}
//circle method
void area(double radius) {
double cirArea = Math.PI * radius * radius;
System.out.println("Area of circle = " cirArea);
}
}
public class Area {
public static void main(String[] args) {
class Triangle extends Shape{
void takeInput(){
Scanner cin = new Scanner(System.in);
System.out.println("Enter base of Triangle: ");
this.b = cin.nextInt();
System.out.println("Enter height of Triangle: ");
this.h = cin.nextInt();
area(b, h);
}
}
class Square extends Shape{
void takeInput(){
Scanner cin = new Scanner(System.in);
System.out.println("Enter side of Square: ");
this.s = cin.nextInt();
area(s);
}
}
class Circle extends Shape{
void takeInput(){
Scanner cin = new Scanner(System.in);
System.out.print("Enter radius of Circle: ");
this.r = cin.nextDouble();
area(r);
}
}
}
}
CodePudding user response:
you just defined the Classes you also need to make a Objekt with those classes
Circle c = new Circle();
c.takeInput();
CodePudding user response:
Maybe it's better to use an abstract method in Shape
. Something like the following:
abstract class Shape {
abstract void area(double... params);
}
and
public class Circle extends Shape {
public static void main(String[] args) {
Circle c = new Circle();
double radius = 1;
c.area(radius);
}
@Override
void area(double... params) {
if (params.length != 1) {
throw new IllegalArgumentException("Expected one argument as parameter (the radius).");
}
System.out.println("Circle area: " (Math.PI * Math.pow(params[0], 2)));
}
}