0

I'm working on an assignment for class, and it's working on classes to make us call items from other classes as often as possible. I'm trying to call public int side(int number) from another public int, but it won't let me.

I can't rearrange the code to edit public int side at all because it was included in part of the assignment

package lab6_carl6188;

class Polygon 
{ 
  private int[] sideLengths; 

  public Polygon(int sides, int ... lengths) 
  { 
    int index = 0; 
    sideLengths = new int[sides]; 
    for (int length: lengths) 
    { 
      sideLengths[index] = length; 
      index += 1; 
    } 
  } 

  public int side(int number) 
  { 
    return sideLengths[number]; 
  } 

  public int perimeter() 
  { 
    int total = 0; 
    for (int index = 0; index < sideLengths.length; index += 1) 
    { 
      total += side(index); 
    } 
    return total; 
  } 
}

class Rectangle{
    private int[] sideLengths;
    public Rectangle(int length1, int length2) {
        sideLengths[0] = length1;
        sideLengths[1] = length2;
    }
    public int area() {
        int total = 1;
        for(int x = 0; x < sideLengths.length; x++) {
            total = total * Polygon.side(x);
        }
    }

    }

}

This whole block is the code. I'm not allowed to edit class Polygon in any way.

public int side(int number) 
  { 
    return sideLengths[number]; 
  } 

is what I want to call, and I'm calling it this way:

public int area() {
        int total = 1;
        for(int x = 0; x < sideLengths.length; x++) {
            total = total * Polygon.side(x);
        }
    }

My error is "Cannot make a static reference to the non-static method side(int) from the type Polygon"

  • `side` is a non-static method in the `Polygon` class. That means it belongs to **instances** (objects) of this class. You must call it on an instance created with `new`. It makes no sense to call it on the class, as it is not static. Think about `Person.getName()` being meaningless, as you could have hundreds of different persons. Instead, `Person john = new Person("John");` and then `john.getName()`. – Zabuzard Oct 21 '19 at 22:38
  • 1
    Should `Rectangle` be a subclass of `Polygon` or what was your assignment exactly? – Mick Mnemonic Oct 21 '19 at 22:39
  • Most likely you need to change `class Rectangle` to `class Rectangle extends Polygon`. Then you can just do `total = total * side(x);`. But this won't give you the correct value of `area()`. – Code-Apprentice Oct 21 '19 at 22:40

1 Answers1

2

Polygon.side is not a static method. That means you can't call it on the class object but instead you need to create an instance of the class.

Polygon polygon = new Polygon();
polygon.side(x);
Christian B
  • 102
  • 3