Constructor is being used to create an instance of your class.
If you didn't care about value being edited by multiple places of code and affecting everyone, then you can make the value
a static
and use it without a constructor. It is very important to understand differences between instance variables and static variables, because there are places where static makes sense.
In your case, you're creating an instance of class ExampleConstructor
by calling its constructor and assigning it to variable constructor
. Then changing the "instance variable" value
to 10. You don't have to pass values into the constructor, you can have an empty constructor and set the value after instantiating an object.
If you make the member value
a static
, like static int value;
and use it without a constructor, like ExampleConstructor.value
, it works. But the problem is, if another piece of code sets the ExampleConstructor.value
to say 2828, then every piece of the code after that line will get the 2828 when they println ExampleConstructor.value
.
If you don't want that to happen, where changing by one place of code affecting everywhere else. Then you should define the member value
as instance variable and use a constructor to instantiate an object and use the instance variable.
IMO, your naming of class and variables is prone to causing confusion to a reader.
Check the code block below for a better explanation.
public class HelloWorld{
public static void main(String []args){
System.out.println("Printing static value from TestClass.");
// Observe that the TestClass is not being instantiated to operate on staticValue;
System.out.println("TestClass.staticValue: " + TestClass.staticValue);
changeStaticValue();
System.out.println("\nPrinting static value from TestClass after editing.");
System.out.println("TestClass.staticValue: " + TestClass.staticValue);
TestClass instance1 = new TestClass();
TestClass instance2 = new TestClass(123);
System.out.println("\nPrinting instance value of both instances right after instantiation.");
System.out.println("instance1.instanceValue: " + instance1.instanceValue);
System.out.println("instance2.instanceValue: " + instance2.instanceValue);
instance1.instanceValue = 888;
instance2.instanceValue = 999;
System.out.println("\nPrinting instance values after editing.");
System.out.println("instance1.instanceValue: " + instance1.instanceValue);
System.out.println("instance2.instanceValue: " + instance2.instanceValue);
}
private static void changeStaticValue()
{
TestClass.staticValue = 11111;
}
}
class TestClass
{
public static int staticValue;
public int instanceValue;
public TestClass()
{
}
public TestClass(int instVal)
{
this.instanceValue = instVal;
}
}