Search code examples
javaoopinheritanceencapsulation

How to cube a squared answer using Java inheritance


The directions for our programming activity is this (roughly translated to English):

Directions: Write a program that will compute the square and cube of a user inputted number. Create classes that show the feature of Inheritance and Encapsulation of Java. Create your own declarations.

And so far I've already done the squared number. This is my code:

import java.util.*;

public class Square {

    protected int square;
    
    public int getSquare() {
        return square;
    }

    public void setSquare (int numberToSquare) {
        square = numberToSquare*numberToSquare;
    }  

    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Square number2 = new Square();
        Cube number3 = new Cube();
        
        System.out.println("Enter number to square and cube: ");
        int userNumber = input.nextInt();
        
        number2.setSquare(userNumber);
        number3.setCube(userNumber);
        
        System.out.println("The square of " + userNumber + " is " + number2.getSquare());
        System.out.println("The cube of " + userNumber + " is " + number3.getCube());
    }
    
}

And this is my Cube class:

class Cube extends Square {
    protected int cube;
    
    public int getCube() {
        return cube;
    }
    
    public void setCube (int numberToCube){
        cube = getSquare()*numberToCube;
    }

}

I know my setCube is wrong but that's what I would like to ask: is it possible for me to use the squared answer so I can avoid having to type numberToCube x numberToCube x numberToCube?


Solution

  • Or even a little bit more simple:

    public class Square {
    
        // Value is protected, so you can also see it in the Cube class.
        protected int val;
    
        public Square(int val) {
            this.val = val;
        }
    
        public int calculate() {
            return val*val;
        }
    }
    
    public class Cube extends Square {
    
        public Cube(int val) {
            super(val);
        }
    
        @Override
        public int calculate() {
            super.calculate()*val;
        }
    }
    

    Either way I think this is a missunderstanding of object oriented programming and inheritance, because you use two classes for some very basic calculations. These aren't any objects, that share attributes in the way that OOP should be used.