Question: [Image of Description](https://i.stack.imgur.com/Kc9Ke.png)

The aim is to have the user select a shape (Square, Triangle or Circle) and then enter a boundary length. Once this information has been input I can then calculate the perimeter and area of their choice.

The problem is I don't want to create new variables for the length and area in each class if I don't have to and would rather have the variables declared and then passed into the classes if I can.

Basically I don't want to do it like this,

```
class square {

  double bLength;
  double area;

}

class triangle {

  double bLength;
  double area;

}

class circle {

  double bLength;
  double area;

}

```

Can I declare them outside of the classes and then have the classes use/inherit them or anything?
I must apologise for such a basic question, I am quite new to Java and I can't really think around this one.

Answer: 
The classic solution is to use inheritance:

```
class Shape {
    double bLength;
    double area;

    Shape(double bLength, double area) {
        this.bLength = bLength;
        this.area = area;
    }
}

class Square extends Shape {
    Square(double bLength, double area) {
        super(bLength, area);
    }
    // additional field, methods...
}

// same for the other shapes

```
You can use inheritance for this problem in following way :

Declare a class called Shape from which all other classes would inherit

```
public class Shape {

    public double length = 0;
    public abstract double GetPerimeter();
    public abstract double GetArea();

    public Shape(double length) {
        this.length = length;
    }
}

```

Then have your specialized classes. E.g. :

```
public class Circle extends Shape {
    public Circle(double length) {
        super(length);
    }

    public double GetPerimeter() {
        // Implement the perimeter logic here
    }

    public double GetArea() {
        // Implement the area logic here
    }
}

```

Do this for all classes. This way you have the variable in only one class, and all others inherit from it.

**EDIT**

If you want even further optimization (for instance, you don't want function call overhead), something like perhaps 

```
public class Shape {

    public double length = 0;
    public double perimeter= 0;
    public double area= 0;

    public Shape(double length, double perimeter, double area) {
        this.length = length;
        this.perimeter= perimeter;
        this.area = area;
    }
}

public class Circle extends Shape {
    public Circle(double length) {
        super(length, 2 * Math.PI * length, Math.PI * length * length);
    }
}

```