Hello and thank you for coming and reading my post. I had a question regarding class variables and constructors. I'll post some code so I can show what I mean:
Case 1.)
public class Shape { private int length; private int width; private int height; public Shape(int shapeLength, int shapeWidth, int shapeHeight) { this.length = shapeLength; this.width = shapeWidth; this.height = shapeHeight; // Test to make sure I have no error and embarrass myself on the forums :) System.out.println(this.length + ", " + this.width + ", " + this.height); } }
Case 2.)
Both of these are then run in this class:public class Shape { private static int length; private static int width; private static int height; public Shape(int shapeLength, int shapeWidth, int shapeHeight) { Shape.length = shapeLength; Shape.width = shapeWidth; Shape.height = shapeHeight; // Test to make sure I have no error and embarrass myself on the forums :) System.out.println(Shape.length + ", " + Shape.width + ", " + Shape.height); } }
Now both styles from 1 and 2 achieve the same result. I just don't understand the difference between the two.
It seems that the keyword (static) is the cause of the change, and when I looked up static I found: The static keyword denotes that a member variable, or method, can be accessed without requiring an object of the class to which it belongs.
So.. Does this mean that with the keyword (this), I have to have created an object in order to access the variables? And with static I don't??
Thanks for any help!
This is not for an assignment, I'm just curious.