non-static method getDimensions() cannot be referenced ...
Doing some deeper study on classes and objects. The object here is to get the dimensions of a rectangle, and give the area and perimeter of the rectangle. the tester is giving me a compilation error:
RectangleTest.java:14: non-static method getDimensions() cannot be referenced from a static context
System.out.println(Rectangle.getDimensions());
Can somebody give me some insight?
Thanks.
Code :
//Jeremiah A. Walker
//Find the area and perimeter of a rectangle
public class Rectangle
{
private int width = 1;
private int length = 1;
private int area;
private int perimeter;
//method to set dimensions for our rectangle;
public void setDimensions(int w, int l)
{
width = w;
length = l;
area = w * l;
perimeter = 2 * l * w;
}//end method setDimensions
public String getDimensions()
{
return String.format("%02d:%02d:%02d:%02d", width, length, area, perimeter);
}//end method getDimensions
}//end class Rectangle
Code :
//Jeremiah A. Walker
//Test Rectangle class
public class RectangleTest
{
public static void main(String[] args)
{
//create and initialize a Rectangle object
Rectangle rect1 = new Rectangle();//invokes Rectangle constructor
//output string representations of the time
rect1.setDimensions(10,10);
System.out.print("The dimensions of this rectangle are: ");
System.out.println(Rectangle.getDimensions());
}//end main
}//end class RectangleTest
Re: non-static method getDimensions() cannot be referenced ...
Rectangle is a class. You want to get the dimensions of a particular instance of Rectangle. But the way you're calling it, it looks like you're trying to get the dimensions of the entire Rectangle class, which doesn't make sense since different instances of Rectangle will have different dimensions. And you haven't declared your getDimensions() method static, hence the compiler warning.
Re: non-static method getDimensions() cannot be referenced ...
I declared the method and its associated variables static, but now I get this error:
Rectangle.java:22: unreachable statement
return perimeter;
^
1 error
Re: non-static method getDimensions() cannot be referenced ...
Quote:
Originally Posted by
JeremiahWalker
I declared the method and its associated variables static, but now I get this error:
Rectangle.java:22: unreachable statement
return perimeter;
^
1 error
Why do you want to do that? As Kevin pointed out, do you wish every instance of Rectangle be the same? I'd suggest removing the static, and go back to the original code you posted. RE the error you get - take a look at how you call setDimensions (eg. rect1.setDimensions ) - this is correct syntax for calling an objects method, and the getDimensions call should be similar syntax
Re: non-static method getDimensions() cannot be referenced ...
Re: non-static method getDimensions() cannot be referenced ...
invoke the getDemension() method on the object rather than the class
EDIT: Oh you solved it. nevermind lol