-4

Calculate area of a square or rectangle. Help, so I have to apply inheritance, overriding, perhaps overloading depending on the statement, here when I try to calculate the rectangle's area the result is 0.0 I believe it's because my asignar (assign) method in the subclass isn't overriding the one from the superclass. Also, does this program effectively apply inheritance and overriding(besides the issue i'm having)?

import java.io.*;

class AreaF {
    private double lado; // side

    public void asignar(double b) {
        lado = b;
    }

    public double traerL() {
        return lado;
    }
}

class Cuadrado extends AreaF {
    public double area() {
        double a;
        a = Math.pow(traerL(), 2);
        return a;
    }
}

class Rectangulo extends AreaF {
    private double altura; // height

    public void asignar(double h) {
        double altura = h;
    }

    public double area() {
        double a;
        a = traerL() * altura;
        return a;
    }
}

public class Pro2 {
    public static void main(String[] args) throws IOException {
        double b = 0, h = 0;
        int op;
        Cuadrado obj = new Cuadrado(); // square
        Rectangulo obj2 = new Rectangulo(); // rectangle
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Ingrese la base: ");
        try {
            b = Double.parseDouble(br.readLine());
        } catch (NumberFormatException x) {
            System.out.println(x);
        }
        obj.asignar(b);
         /**
         * 1 - for square
         * 2 - for rectangle
         */
        System.out.println("Ingrese 1 para saber el area de CUADRADO, 2 para RECTANGULO"); 

        op = Integer.parseInt(br.readLine());
        if (op == 1) {
            System.out.println("El area del cuadrado es: " + obj.area()); // sq
                                                                            // area
        } else if (op == 2) {
            System.out.println("Ingrese la altura del rectangulo: "); // height
            try {
                h = Double.parseDouble(br.readLine());
            } catch (NumberFormatException x) {
                System.out.println(x);
            }
            obj2.asignar(h);
            System.out.println("El area del rectangulo es: " + obj2.area()); // rct
                                                                                // area
        } else
            System.out.println("Error!");
    }
}
Jorge Campos
  • 20,662
  • 7
  • 51
  • 77
valery
  • 5
  • 1
  • I'm not sure, but to me class hierarchy looks strange: 1. What is the benefit of class `AreaF` which has "side"? 2. To me looks like `Cuadrado` must be inherited from `Rectangulo` as a square is the edge case of rectangle where both height and width are equals. – Andrej Istomin Mar 30 '16 at 00:37
  • Your main problem is that you created two objects `obj` and `obj2` when you ask to insert the base you only set it up on the `obj` here `obj.asignar(b);` after that you ask if it is a rectangle or a square when the user chose a rectangle you never setted `obj2.asignar(b);` therefore you will always have 0 for a rectangle. – Jorge Campos Mar 30 '16 at 00:49
  • Well, if you want to Square and Rectangle to extend AreaF, I would suggest changing it to an interface with a function to return the area. As it is now, you are technically overriding (add optional `@Override` annotation). – Debosmit Ray Mar 30 '16 at 00:51

3 Answers3

2

I'm not really sure what is the goal of this task, but I would go with the following class hierarchy:

interface Figure { // also abstract class can be used there
    abstract double area();
}

class Rectangle implements Figure {
    private double width;
    private double height;

    Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    double area() {
        return width * height;
    }
}

class Square extends Rectangle {
    public Square(double side) {
        super(side, side);
    }
}

I simplified main method, but I think the idea is clear:

public static void main(String[] args) {
    final Rectangle rectangle = new Rectangle(3, 5);
    System.out.println("rectangle.area() = " + rectangle.area()); // result is 15.0
    final Square square = new Square(3);
    System.out.println("square.area() = " + square.area()); // result is 9.0
}

So, Rectangle overrides area() method of Figure and Square inherits it from Rectangle.

Andrej Istomin
  • 595
  • 6
  • 15
  • 1
    Given the requirements that the OP has mentioned and the design you have implemented, don't you think using an *interface* would be better suited, instead of an *abstract class*? Especially since `Figure` does not have (and/or require) any implemented methods. For more clarity on the distinction between the two, [this link](http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo). – Debosmit Ray Mar 30 '16 at 01:06
  • I agree. Actually my first idea was to create it as an interface(I would definitely do it in production code), but then I changed my mind. I thought that maybe with abstract class the idea of inheritance would be more clear to topic starter. But if at least we two think that interface is better here, I edited my post :) – Andrej Istomin Mar 30 '16 at 01:09
  • Yea, I figured as much. Nice design and answer, either way. :) – Debosmit Ray Mar 30 '16 at 01:12
1

You are neither overloading nor overriding. You're just hiding.

Overloading refers to the addition of a method in a class in which a method with the same name but different signatures already exists.

Overriding refers to the addition of a method marked with the @Override attribute in a class whose super class contains a method with the same name and signature.

Hiding is similar to overriding, but the method added is not marked with @Override, which is what you have done here.

So the answer to this question

does this program effectively apply inheritance and overriding(besides the issue I'm having)?

is no.

I think you should change your whole design.

Note: All of below is my own opinion.

AreaF should be an abstract class, or even an interface. I think an interface is more suitable, but it seems like that your assignment needs you to use inheritance. So let's change it to an abstract class:

public abstract class AreaF {
    public abstract double getArea();
}

I see that you have a square and a rectangle as the base class of AreaF. Let's implement them as well:

public class Square extends AreaF {
    private double length;
    public double getLength() { return length; }
    public void setLength(double length) { this.length = length; }
    @Override // I overrode the getArea method in the super class
    public double getArea() {
        return getLength() * getLength();
    }
}

And here is the Rectangle class:

public class Rectangle extends AreaF {
    private double width, height;

    // public getters and setters for width and height. You know what I mean.
    @Override
    public double getArea () {
        return getWidth() * getHeight();
    }
}

Then you can use the methods accordingly and get the correct result.

Sweeper
  • 145,870
  • 17
  • 129
  • 225
  • What? @Override is optional in Java (good practice, but optional). What's the semantic difference between "hiding" and "overriding" as you define them? – Silvio Mayolo Mar 30 '16 at 00:49
  • What is the benefit of having different `getArea()` methods for `Rectangle` and `Square` if they do exact the same thing? – Andrej Istomin Mar 30 '16 at 01:00
0

Your code had lots of problems. 1)indent 2)English names. 3)you had a logic Error. Object1.lado=a, Object1.altura=0; while Object2.lado=0, Object2.altura=h ==> obj2.area=0... (this is your mistake!).

here is a good code. look at it and if you have any quotation feel free to ask.

import java.io.*;

class AreaF {
    private final double lado; 

    public void asignarLado(double b) { //give mingfullnames (better in english!)
        lado = b;
    }

    public double traerL() {
        return lado;
    }
}

class Cuadrado extends AreaF {
    public double areaCuadrado() {
        double a;
        a = Math.pow(traerL(), 2);
        return a;
    }
}

class Rectangulo extends Cuadrado {
    private double altura; 

    public void asignarAltura(double h) {
        double altura = h;
    }

    public double areaRectangulo() {
        double a;
        a = traerL() * altura;
        return a;
    }
}



public class Pro2 {
    public static void main(String[] args) throws IOException {
        double b = 0, h = 0;
        int op;
        Cuadrado obj = new Cuadrado(); // square

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.println("Ingrese la base: ");
            b = Double.parseDouble(br.readLine());
            obj.asignarBase(b);

            System.out.println("Ingrese la altura del rectangulo: "); // height
            h = Double.parseDouble(br.readLine());
            obj.asignarAltura(h);

            System.out.println("Ingrese 1 para saber el area de CUADRADO, 2 para RECTANGULO");
            op = Integer.parseInt(br.readLine());

             if (op == 1) {
                System.out.println("El area del cuadrado es: " + obj.areaCuadrado());
             else if (op == 2) {
                System.out.println("El area del rectangulo es: " + obj.areaRectangulo());
            }
            else
                System.out.println("Error!");
            }
        } catch (NumberFormatException x) {
            System.out.println("Wrong arguments!");
        }finally{
            br.close; //allways close input resurce! 
        }

    }
}

///------------------------------------------- And this is real O.O design. I used an interface with one method called Area. and two classes cube, and rect classes. this is the real way to go.

public interface Area{
    public double getArea();
}

class Cuadrado implements Area {
    double base;

    public Cuadrado(double base){
        setBase(base);
    }

    public void setBase(double base) {
        this.base = base;
    }

    @Override
    public double getArea() {
        // TODO Auto-generated method stub
        return base*base;
    }


}

class Rectangulo extends Cuadrado {

    private double hight;

    public Rectangulo(double base,double hight){
        super(base);
        this.hight = hight;
    }

    public void setParams(double base,double hight) {
        this.base = base;
        this.hight = hight;
    }

    @Override
    public double getArea() {
        // TODO Auto-generated method stub
        return base*hight;
    }
}


public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        try {
            System.out.println("Ingrese la base: ");
            double b = Double.parseDouble(br.readLine());

            System.out.println("Ingrese la altura del rectangulo: "); // height
            double h = Double.parseDouble(br.readLine());

            System.out.println("Ingrese 1 para saber el area de CUADRADO, 2 para RECTANGULO");
            int op = Integer.parseInt(br.readLine());

             if (op == 1) {
                Area cuadrado = new Cuadrado(b); // square
                System.out.println("El area del cuadrado es: " + cuadrado.getArea());
             }
             else if (op == 2) {
                Area rectangulo = new Rectangulo(b,h);
                System.out.println("El area del rectangulo es: " + rectangulo.getArea());
            }
            else{
                System.out.println("Error!");
            }
        } catch (NumberFormatException x) {
            System.out.println("Wrong arguments!");
        }finally{
            br.close(); //allways close input resurce! 
        }

    }
}
Alex
  • 119
  • 1
  • 8
  • 4
    as an answer, this is quite low quality; should be a comment. – Debosmit Ray Mar 30 '16 at 00:48
  • Firstly, I didn't give a '-1'. I chose to notify you instead. Secondly, that is simply **not** a reason to put a comment as an answer. – Debosmit Ray Mar 30 '16 at 00:54
  • but my answer is true... the root of the problem is indeed lies in the fact that ob1 and obj2 are to different objects.. :) His code has X10000 problems. but the biggest one is obj1 and obj2 are two distinct Objects. – Alex Mar 30 '16 at 00:57
  • Please refer to the other answers posted in this thread, especially the one by @AndrejIstomin. Please also look at [How to answer](http://stackoverflow.com/help/how-to-answer). – Debosmit Ray Mar 30 '16 at 01:02
  • Good point about bad code formatting. I would also agree with using English language in code. But I completely disagree with the form of your comment. It's impolite. Comment which is starting with words: "I did not look at you code entirely..." is really worth to get "-1", isn't it? – Andrej Istomin Mar 30 '16 at 01:04
  • I did not mean to be impolite, I meant that maybe there other errors, but for now i see this logic error... did not mean to be impolite. – Alex Mar 30 '16 at 01:44