I'm aware this question has been asked many, many times and I've read loads of answers but I can't get my head around how to fix my problem. Here is my code:
public class Circle
{
public int diameter;
public int xPosition;
public int yPosition;
public String color;
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
}
public void toString()
{
System.out.println("The diameter of the circle is " + Circle.diameter);
System.out.println("The x position of the circle is " + Circle.xPosition);
System.out.println("The y position of the circle is " + Circle.yPosition);
System.out.println("The colour of the circle is " + Circle.color);
}
public static void main(String[] args)
{
Circle c1 = new Circle();
c1.toString();
}
}
I did originally fix the issue by changing:
public class Circle
{
public int diameter;
public int xPosition;
public int yPosition;
public String color;
}
to
public class Circle
{
public static int diameter;
public static int xPosition;
public static int yPosition;
public static String color;
}
Whilst this does work, I feel it's not a good way to do it. I've read something about instance variables but I'm not sure how to do this.
Thanks.
The problem is with with toString()
function:
System.out.println("The diameter of the circle is " + Circle.diameter);
System.out.println("The x position of the circle is " + Circle.xPosition);
System.out.println("The y position of the circle is " + Circle.yPosition);
System.out.println("The colour of the circle is " + Circle.color);
You are referencing non-static variable with Class reference. Just replace Circle
with this
. Have a look Understanding Instance and Class member
tutorial
Edit:
Strangely, it's not letting me use the name toString() because "toString() in Circle cannot override toString() in object". It works with any other name though
yes because, toString()
method is declared in Object
class which is super class for all of the java class. This method has a return type with String
, where instead you are using void
. So either you will have to change the return type to String
or change the function name to anything other.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments