Home > Net >  Creating Superclasses and Subclasses Java quesiton
Creating Superclasses and Subclasses Java quesiton

Time:12-23

i started learning Java in university and we have an assignment that requires us to use a Superclass for Shape and Subclass that extend the shape.

This is the full questions:

Create a super class “Shape” from which you derive two subclasses “Square” and “Rectangle” with functions to calculate the square area and the rectangle area. In addition, to the function “toString” to display the square and rectangle info. Derive another sub class “Cube” from square with a function to calculate its area and a function “toString” to display the cube info."

What we need to do is calculate the shapes using the classes. Where should I start or move forward to solve the assignment?

This is where I think I should start, but need some guidance

public class Shapes {
  class Shape {

  }

  class Rectangle extends Shape {

  }

  class Square extends Shape {

  }
}

CodePudding user response:

First, Shape class should be abstract, since you won't create any specific object of this class and you'll only use it as a "canvas". This class has to have an abstract method, let's call it getArea(), that you'll have to override in your child classes to accomodate to the specified requirements for each kind of shape.

The toString() method belongs to Object class, since every class in Java extends from Object, you don't have to define anything, just override this method to return the desired String in every child class.

According to the definition you have post, the Cube class would be a composition of Square (a cube is composed by squares, but it's not a square), so I'd extend it from Shape and define it as a List or an array of 6 Square, so the getArea() of Cube would be the summatory of every Square area in it.

CodePudding user response:

Putting aside the quality of the question:

You have a Shape class that will contain a method calculateSomething(). Shape does not define a specific shape so most likely you can return a -1 or 0?

Now, we can determine that the method of the Shape class does not provide us with any real value/info. Even if you create a Shape shape = new Shape() object and call its method, it does not help us at all.

Instead it provides us with a method that each subclass has to override in order to get the intended results.

What does that mean and how it works?

For you to not always have to do Rectangle rect = new Rectangle() for every single class and object, the Rectangle becomes a subclass of the Shape class.

This enables you to later do Shape rect = new Rectangle(). The big benefit of this is that you create an abstraction mechanism, meaning that you have a lot of shapes, either rectangles or triangles etc, but they all are Shape objects in the end.

So later you can just do:

Shape rect = new Rectangle();
Shape triangle = new Triangle();
rect.calculate();
triangle.calculate();

Instead of the more meticulous:

Rectangle rect = new Rectangle();
Triangle triangle = new Triangle();
rect.calculate();
triangle.calculate();

The former can further be utilised by:

// Putting all the objects in a list
List<Shape> shapes = new ArrayList<>();

// Create objects and add them
Shape rect = new Rectangle();
Shape triangle = new Triangle();
shapes.add(rect);
shapes.add(triangle);

As you can see for yourself, it is easier to handle and iterate over a list with all the elements being of type/class Shape.

// Basic example
for (Shape shape : shapes)
    shape.calculateSomething();

Imagine if you had a hundred different shapes except Rectangle and Triangle. The latter method, without using inheritance, would quickly come to consume your project in an ever ending trial of maintenance and code changing.

By utilising inheritance otherwise, you can increase your Shape classes as much in quantity as you want and the same methods that used to work for a Shape, would still work for all the future new objects.

How does it work in practise? How do i create a subclass?

As you already know you can link your classes through the extend keyword. But that is only the start.

To be able to utilize the inheritance, you will have to overwrite the method of your choosing, in the child class.

Take for instance the previous example:

Shape rect = new Rectangle();
rect.calculate();

But that raises the question, how can you get the correct value of calculate() method, when Shape class has a -1 or 0 returning from it and rect variable is now of type Shape?

Easily, you can override a method of the parent class through the @Override tag and by implementing the same method again on the child class but with different calculations. Example:

class Shape {
    
    public void calculate() { return 0; }
}

class Rectangle extends Shape {
     
    @Override
    public void calculate() { return 2; }
}

Note that the name, variables etc of the method must be identical.

Now in the case of:

Shape rect = new Rectangle();
rect.calculate();

the calculate() method will return the number 2. This happens because even though the rect object is of type Shape, it is also a Rectangle. Every Rectangle is a Shape. So when you try to call the desired method, the program knows to choose the overrided method of the Rectangle class, because in essence it is a Rectangle, covered by the abstraction Shape.

This works for any number of Shape subclasses, each with their own unique implementation of the method.

Also note that a Rectangle subclass can have its own private fields that are used in the other methods:

class Rectangle extends Shape {
    private int height;
    private int width;

    // constructor
    public Rectangle(int h, int w) {
         this.height = h;
         this.width = w;
    }

    @Override
    public void calculate() { 
            return this.w * this.h; 
    }
}

So to answer your question, you just override the methods you want for each class as you desire. If a method is not overriden, then the original of the Shape parent class is run.

I hope this shined a little bit of light in your confusion towards abstraction and inheritance.

PS: I know that you might be confused, but there are hundreds of answers and forums out there explaining this exact thing and that is how we all learned it. It needs time unfortunately but you will have a deeper understanding if you look at something yourself. I'm sure you have taken a taste of what is defined as 'wrong' or 'bad' to ask in here and that you will be more susceptible into studying it yourself in the future, considering there is material needed. I just tried to reach out to you because i have been in your place and believed i could make a difference with my approach.

If you have anything else to add or something to correct, it is always welcome in the comments section.

Edit: As mentioned by the other guy that answered, the Shape class can and should be an abstract one. I just assumed you wanted it to be a normal one.

  • Related