Interface and Inheritance compile time error - java

I have written a short program that uses inheritances and interface relationships to calculate the area and the perimeter of user selected shapes. I receive a compile time error when I attempt to compile the following classes.
Class Square
public class Square extends Quadrilateral
{
double side1 =this.side1;
double side2 = this.side2;
double perimeter = this.perimeter;
double area = this.area;
Square(double instanceSide1, double instanceSide2) {
side1 = instanceSide1;
side2 = instanceSide2;
}
#Override
public double area()
{
area = side1 *side2;
return area;
}
#Override
public double perimeter() //math equation for determing perimeter
{
this.perimeter = (side1 * 2) + (side2 * 2) ;
return perimeter;
}
}
Here is my Quad class
public abstract class Quadrilateral implements Polygon{
}
Here is the Polygon Class
public interface Polygon {
abstract void area();
abstract void perimeter();
}
Here is the Tester Class that I've built to run the code.
public static void main(String[] args) //Constructor initalizing main class
{
int numberSides;
int length;
int base;
Scanner sides = new Scanner(System.in); //Initializing Scanner Class
/**
* Do/while loop for selecting a 3 or 4 sided object
*/
do
{
System.out.println("Do you want a 3 or 4 sided shape? (Type either "
+ "3 or 4).");
numberSides = sides.nextInt();
} while (numberSides < 3 || numberSides > 4);
if (numberSides == 3) {
System.out.println("How long are the sides that are the same lenth?");
length = sides.nextInt();
System.out.println("How wide is the base? (whole numbers");
base = sides.nextInt();
IsoscelesTriangle Isoc = new IsoscelesTriangle(length, base);
System.out.println("The area of the isocolese triangle is: " + Isoc.area());
System.out.println("The perimeter of the isocolese triangle is: " + Isoc.perimeter());
} else {
System.out.println("How long are the sides are the same?");
length = sides.nextInt();
System.out.println("How wide is the base?");
base = sides.nextInt();
if (length == base) {
Square Quad = new Square(length, base);
System.out.println("The area of the square is: " + Quad.area());
System.out.println("The perimeter of the square is: " + Quad.perimeter());
} else {
Rectangle Quad = new Rectangle(length, base);
System.out.println("The area of the rectangle is: " + Quad.area());
System.out.println("The perimeter of the rectangle is: " + Quad.perimeter());
}
}
}
}

Your class that implements the interface does not have methods that matches the interface. The interface's methods return void, while the class returns double. They must match exactly, and probably it is the class that's right and the interface that's wrong -- change the interface method declarations to return double.
In the future, you will want to post all error / exception messages if you have a question about them. It will help us save time and get you better answers.

Related

Why is the output of this polymorphism program shows 0 in this Java program?

I am trying to integrate the topics like Dynamic Polymorphism, Inheritance and switch statements altogether in a single program where, I am getting an output but the result is always 0 in the console window. There is no error too. May be it is a logical error but I am not sure. I am just at the beginning phase of learning Java.
import java.io.IOException;
import java.util.Scanner;
// Dynamic Polymorphism implementation with switch case
public class Main {
public static void main(String[] args) throws IOException{
Shapes myShape = new Shapes();
Shapes myTriangle = new Triangle();
Shapes myCircle = new Circle();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the Shape you would like to get the area of: ");
System.out.println("Your Choices are : 1=Triangle, 2= Circle");
int response = scanner.nextInt();
switch(response)
{
case 1 : System.out.println("Enter the base of the triangle: ");
scanner.nextDouble();
System.out.println("Enter the height of the triangle: ");
scanner.nextDouble();
System.out.println(myTriangle.area());
break;
case 2 : System.out.println("Enter the radius of the circle: ");
scanner.nextDouble();
System.out.println(myCircle.area());
break;
default : System.out.println("Invalid Input");
System.out.println(myShape.area());
}
scanner.close();
}
}
class Shapes {
double base;
double height;
double radius;
public double area() {
System.out.println("Formula for Area of triangle is 1/2 * base * height");
System.out.println("Formula for Area of Circle is 3.14 * radius * radius");
return 0;
}
}
class Triangle extends Shapes{
double x = 0.5*base*height;
#Override
public double area() {
System.out.println("Area of Triangle is : ");
return x;
}
}
class Circle extends Shapes{
double y = 3.14*radius*radius;
#Override
public double area() {
System.out.println("Area of Circle is: ");
return y;
}
}
```
You missed to assign value to the base, height, and radius i.e. you missed something like this:
myTriangle.base = scanner.nextDouble();
Secondly, your area() method should compute on the fly. Otherwise, the area value will always be 0, as originally all the base, height, and radios are 0. So for Triangle class, it should be like this:
class Triangle extends Shapes {
#Override
public double area() {
System.out.println("Area of Triangle is : ");
return 0.5 * base * height;
}
}
You should do the same for Circle.

Basic Question - Setting object's traits in a method and calling that method in the test/helper class - Java

I am learning very basic Object-oriented programming with Java, I have a triangle object called triangle1 and I set its values in my helper class, however, I want to use a setter and getter in my main class to change triangle1's values. I am just confused about how I call that method to show the updated values.
This is my main class where I have created my object of Triangle. Right under that I am trying to get the values and change them to 15.5,15.5,15.5, and green. I realize I am probably doing this wrongly.
public class Triangle extends codeAssignHelper{
public double base;
public double side1;
public double side2;
public String colour;
Triangle(double base, double side1, double side2, String colour){
this.base = base;
this.side1 = side1;
this.side2 = side2;
this.colour = colour;
}
public void setBase(double base){
this.base = 15.5;
}
public void setSide1(double side1){
this.side1 = 15.5;
}
public void setSide2(double side2){
this.side2 = 15.5;
}
public void setColour(String colour){
this.colour = "green";
}
public double getBase(){
return this.base;
}
public double getSide1(){
return this.side1;
}
public double getSide2(){
return this.side2;
}
public String getColour(){
return this.colour;
}
public static void main(String[] args){
}
}
This is my helper class and I have printed triangle1 and triangle2 and all I want is to reprint triangle1's values but updated. I realize it is probably not understanding I want to update triangle1 specifically.
class codeAssignHelper{
public static void main(String[] args){
Triangle triangle1 = new Triangle(1.0,1.0,1.0,"black");
Triangle triangle2 = new Triangle(3.0, 4.0, 5.0, "red");
System.out.println("Welcome to the Triangle tester!");
System.out.println("-------------------------------------------------------");
System.out.println("This program will instantiate objects of a triangle and test all of the methods of the Triangle class.");
System.out.println("-------------------------------------------------------");
System.out.println("For triangle1 length of base is: " + triangle1.base);
System.out.println("For triangle1 length of side 1 is: " + triangle1.side1);
System.out.println("For triangle1 length of side 2 is: " + triangle1.side2);
System.out.println("For triangle1 colour is: " + triangle1.colour + "\n");
System.out.println("Triangle2:");
System.out.println("Base: " + triangle2.base);
System.out.println("Side1: " + triangle2.side1);
System.out.println("Side2: " + triangle2.side2);
System.out.println("Colour: " + triangle2.colour + "\n");
//MY PROBLEM - Need to update triangle1's values here
System.out.println("Testing setter methods on triangle1.");
System.out.println("Triangle1:");
System.out.println("Base: " + triangle1.getBase());
System.out.println("Side1: " + triangle2.getSide1());
System.out.println("Side2: " + triangle2.getSide2());
System.out.println("Colour: " + triangle2.getColour() + "\n");
}
}
Expected output:
Welcome to the Triangle tester!
This program will instantiate objects of a triangle and test all of the methods of the Triangle class.
For triangle1 length of base is: 1.0
For triangle1 length of side 1 is: 1.0
For triangle1 length of side 2 is: 1.0
For triangle1 colour is: black
Triangle2:
Base: 3.0
Side1: 4.0
Side2: 5.0
Colour: red
Testing setter methods on triangle1.
Triangle1:
Base: 15.5
Side1: 15.5
Side2: 15.5
Colour: green
You simply need to call the setters like this, before printing the values out with the getters again:
triangle1.setBase(15.5);
triangle1.setBase(15.5);
triangle1.setSide2(15.5);
triangle1.setColour("green");
I see that you have hardcoded the setters, to set specific values and ignoring the parameter. Maybe that was just for testing purposes, but it should be like this:
public void setBase(double base){
this.base = base;
}
same goes for the other setters of course.
Lastly the data elements of the Class should be private, which is the reason you implement setters and getters in the first place, so only methods from the objects own class can mess with the values of its elements.
So like this:
private double base;
private double side1;
private double side2;
private String colour;

Designing a class named Triangle in Java [duplicate]

This question already has answers here:
Constructor cannot be applied to given types?
(3 answers)
Closed 2 years ago.
Design a class named Triangle that extends GeometricObject. This class contains:
a. Three double data fields named side1, side2, and side3 with default values 1.0 to denote three sides of the triangle.
b. A no-arg constructor that creates a default triangle.
c. A constructor that creates a triangle with the specified side1, side2 and side3.
d. The accessor methods for all three data fields.
e. A method named getArea() that returns the area of this triangle.
f. A method named getPerimeter() that returns the perimeter of this triangle.
g. A method named toString() that returns a string description for the triangle.
The formula for computing the area of the triangle is:
s = (side1 + side2 + side3)/2;
area = s(s – side1) (s – side2) (s – side3)
The toString() method is implemented as follows:
return “Triangle: side1 = “ + side1 + “side2 = “ + side2 + “side3 = “ + side3;
Write a test program that prompts the user to enter three sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input. The program should display the area, perimeter, color, and true or false to indicate whether it is filled or not.
I have tried this question and the codes are as below, but there is an error in the Triangle class and i do not know how to fix it.
//Triangle Class
public class Triangle extends GeometricObject
{
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
public Triangle()
{
}
public Triangle(double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1()
{
return side1;
}
public double getSide2()
{
return side2;
}
public double getSide3()
{
return side3;
}
public void setSide1(double side1)
{
this.side1 = side1;
}
public void setSide2(double side2)
{
this.side2 = side2;
}
public void setSide3(double side3)
{
this.side3 = side2;
}
public double getArea()
{
double area,s;
s = (side1+side2+side3)/2;
area = Math.sqrt(s * (s- side1) * (s - side2) * (s - side3));
return area;
}
public double getPerimeter()
{
return side1 + side2 + side3;
}
public String toString()
{
return " Triangle: Side 1 = " + side1 + " Side 2 = " + side2
+ " Side 3 = " + side3;
}
}
//GeometricObject Class
public class GeometricObject
{
protected String color = "white";
protected boolean filled;
public GeometricObject(String color, boolean filled)
{
this.color = color;
this.filled = filled;
}
//getColor()
public String getColor()
{
return color;
}
//setColor
public void setColor(String color)
{
this.color = color;
}
//isFilled
public boolean isFilled()
{
return filled;
}
//setFilled
public void setFilled(boolean filled)
{
this.filled = filled;
}
}
//Test Program
public class Lab82
{
private double side1 = 1.0;
private double side2 = 1.0;
private double side3 = 1.0;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter three sides of the Triangle");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
System.out.println("Enter the color of the Triangle");
String color = input.next();
System.out.println(" Is the Triangle filled? Reply with 'True' or 'False' ");
String filled = input.next();
Triangle triangle = new Triangle(side1, side2, side3);
System.out.println("The Triangle Sides are \n side 1: " + triangle.getSide1() + "\n Side 2: " + triangle.getSide2() + "\n Side 3: " + triangle.getSide3());
System.out.println("The Triangle's Area is " + triangle.getArea());
System.out.println("The Triangle's Perimeter is "+ triangle.getPerimeter());
System.out.println("The Triangle's Color is " + triangle.getColor());
System.out.println("Is the Triangle filled? " + triangle.isFilled());
}
}
The errors that i get are these :
When your class is extending another which doesn't have a default (no-argument) constructor, you should tell java how to construct its parent class when constructing an instance of the child class. In your case, java doesn't know what to give for color and filled to the parent constructor.
You should call the parent constructor in all of the child class's constructors usingsuper keyword like this:
public class Triangle extends GeometricObject
{
// ...
public Triangle()
{
super(someColor, someFilled);
}
// ...
}

Where to put Scanner class

As a new student to Java I have bean practicing writing methods and then calling them from a different class. I would like to know how to have the radius determined by user input. I understand I need to use the Scanner class but I'm not sure which class to import the Scanner in and where to put the following bit of code.
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
FIRST FILE - My Methods
package circle;
public class Circle {
private double radius;
final double pi;
public Circle(double radiusIn, double piIn) {
radius = radiusIn;
pi = piIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * pi * radius;
}
public double calculateArea() {
return pi * radius * radius;
}
}
SECOND FILE
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
myCircle = new Circle(3, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Typically you declare variables where you need them in this case that means in the main method where the rest of the user interaction takes place.
package circle;
public class CircleTest {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
}
Also Math.PI is a much more accurate approximation of pi. Use that instead of relying on the user to pass in the correct value:
package circle;
public class Circle {
private double radius;
public Circle(double radiusIn) {
radius = radiusIn;
}
public double getRadius() {
return radius;
}
public double calculateDiameter() {
return radius + radius;
}
public double calculateCircumference() {
return 2 * Math.PI * radius;
}
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Think of an Object as an object, like an apple or a toothbrush.
class Circle is a defintion of an Object; it's a description that attempts to match reality. The predefined Java Object is like anything you might find in reality, you can't call eat() on an Object (in the real world) because it might be an apple, but it might be a toothbrush (or a circle).
Therefore, place the code where it makes sense as if it were a real world object. You want to retrieve user input. Does a circle know how to read user input? No!
You call your other class CircleTest. But what it really is, is CircleCreationApplication; that might be a better name for it. In an application that creates circles, you would receive user input. So that is where the code can go. Once you have your user input, you can use that to create the circle.
package circle;
public class CircleCreationApplication {
public static void main(String[] args) {
Circle myCircle;
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter());
System.out.println("Circle circumference is "
+ myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
userInput.close();
}
}
Note: #ratchetfreak's answer has some other good things. Please read that as well
I think the user interaction code goes into the main class. That's where you handle the workflow, depending on user input. What you actually want is to remove the hardcoded radius (3) and read the value from the user using the Scanner, right?
Then your code snippet goes in the main method, right before instantiating the Circle object.
public static void main(String [] args)
{
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter radius");
int radius = userInput.nextInt();
Circle myCircle;
myCircle = new Circle(radius, 3.14159);
System.out.println("Circle radius is " + myCircle.getRadius());
System.out.println("Circle diameter is " + myCircle.calculateDiameter ());
System.out.println("Circle circumference is " + myCircle.calculateCircumference());
System.out.println("Circle area is " + myCircle.calculateArea());
}
You would want to import the scanner and add the code to the second file. Then you can use radius as argument to the Circle constructor instead of just 3.

OOP advice - should I change how my program runs?

below I have a small program i wrote for working out the area of shapes....
My question is this the right way to do it, a friend did similar and had multiple shapes which inherited from main shape. OOP? is mine ok as i will only ask the area of a shape and no more? and how would i change this to make it more OO?
Main Prog /////
package areaprog;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Mainprog {
public static void main (String [] args){
//Area Menu Selection
System.out.println("What shape do you need to know the area of?\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
//User input for menu
Scanner reader = new Scanner(System.in);
System.out.println("Number: ");
//Menu syntax checking
while (!reader.hasNextDouble())
{
System.out.println("Thats not a number you tool.\n");
System.out.println("Now pick again\n" +
"1: Square?\n" +
"2: Rectangle?\n" +
"3: Triangle?\n" +
"4: Circle? \n" +
"5: Exit\n"
);
reader.next(); //ask for next token
}
double input = reader.nextDouble();
reader.nextLine();
//Depending on user selection, depends on what method is called using switch.
Scanner scan = new Scanner(System.in);
//Square selection and InputMismatch Exception
try {
if (input == 1){
System.out.println("What is a length of 1 side of the Square?\n");
double s1 = scan.nextDouble();
double SqAns = AreaCalculator.getSquareArea(s1);
System.out.println("The area of you square is: " + SqAns);
}
}
catch (InputMismatchException e)
{
System.out.println("Why are you trying to be clever? use an interger");
}
//Rectangle selection
if (input == 2){
System.out.println("What is the width of your rectangle?.\n");
double r1 = scan.nextDouble();
System.out.println("What is the height of your rectangle?\n");
double r2 = scan.nextDouble();
double RecAns = AreaCalculator.getRectArea(r1, r2);
System.out.println("The area of your rectangle is: " + RecAns);
}
//Triangle selection
if (input == 3){
System.out.println("What is the base length of the triangle?.");
double t1 = scan.nextDouble();
System.out.println("What is the height of your triangle?");
double t2 = scan.nextDouble();
double TriAns = AreaCalculator.getTriArea(t1, t2);
System.out.println("The area of your triangle is " + TriAns);
}
//Circle selection
if (input == 4){
System.out.println("What is the radius of your circle?.");
double c1 = scan.nextDouble();
double CircAns = AreaCalculator.getCircleArea(c1);
System.out.println("The area of your circle is " + CircAns);
}
//Exit application
if (input == 5){
System.out.println("Goodbye.");
}
}
}
AreaCalculator.java ////
package areaprog;
public class AreaCalculator {
public static double getRectArea(double width, double height) {
double aValue = width * height;
return aValue;
}
public static double getCircleArea(double radius){
double PI = Math.PI;
double aValue = PI * Math.pow(radius, 2);
return aValue;
}
public static double getSquareArea(double side) {
double aValue = Math.pow(side, 2);
return aValue;
}
public static double getTriArea(double base , double height) {
double aValue = (base/2)* height;
return aValue;
}
}
Having multiple classes inheriting from a single base class or interface is definitely a better design here. Use classes to encapsulate given functionality or objects(in that case triangle, square etc. Also when you have multiple classes sharing some functionality better extract it as a common interface to achieve better level of abstraction.
The simple answer is to use an interface of 'shape' like this
interface Shape {
double[] dimensions;
double calcArea();
}
And have all your shapes implement this interface.
say
class Circle implements Shape {
...
}
and implement different calcArea() methods for each shape
In your runner, you init a Circle, box, etc...
When you need area, you don't have to care about which shape is actually behind it, just call the method shape.calcArea() and it will find the right one.

Categories

Resources