0

I need to understand the constructor and instance variables. My question is constructor is initialized in line 1 rather I can do it by creating instance variable in line 2. Why I need to initialize value by using constructor instead I can initialize value by using instance variable?

class ExampleConstructor{
    int value;
    ExampleConstructor(int value){
        this.value=value;
    }
}
public class Main{
    public static void main(String[] args){
        ExampleConstructor constructor=new ExampleConstructor(100);/*line 1*/
        System.out.println(constructor.value);
        constructor.value=10;/*line 2*/
        System.out.println(constructor.value);
    }
}
user10506901
  • 1
  • 1
  • 4
  • Are you asking why you can't just do `int value = 10;`? Because you can. The constructor just allows you to initialize the value when you create the object – GBlodgett Dec 18 '18 at 14:48
  • You can absolutely do it. Just use an empty constructor. You need to use the constructor to instantiate a instance because your class is not a static class and you are calling it from a static method (main). – Sai Puli Dec 18 '18 at 14:51
  • You can see it like giving birth to something, or creating it. to create something, oviously you need ingredients, or else your creation will be missing important things. And you can't edit the creation attributes before giving birth to it (the magical `new` operator). That's all. – Incepter Dec 18 '18 at 14:52
  • You should read this about encapsulation : https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors – Djory Krache Dec 18 '18 at 14:55
  • I think you should remove the word "Contstructor" from the name of your class. It's only going to cause confusion and misunderstanding when you ask questions about the Constructor constructor. – Solomon Slow Dec 18 '18 at 15:51

3 Answers3

0

Its better sometimes.Your line 2 is more like setter for example constructor.setValue(2);

Now look:

MyConstructor myConstructor  = new MyConstructor(2,3,5,"This is my cons");
//or
myConstructor.int1 = 2;
myConstructor.int2 = 3;
myConstructor.int3 = 5;
myConstructor.string1 = "This is my cons";

You have four lines in one line.

Also we souldn't access to the fields like this, we should use getters and setters.

When you call the constructor like this you just assign value to the field when object is created. When you use setters you can access fields any time you want.

Sry for my english. I hope you understand.

MrFisherman
  • 720
  • 1
  • 7
  • 27
0

Sometimes you need to make sure that variables are within some range. For example when you got RandomObject with field probability, you need to make sure that probability between 0 and 1. The second reason, sometimes we want to make sure that field cannot be changed (to prevent bugs) from outside of class. Therefore we can't assign value from outside of class, so we need to do it using constructor (or methods). The third thing is that sometimes we use same argument to calculate few fields (ex. area and side). There are a lot of other reason like preventing duplication of code, making code easier to read or mentioned earlier encapsulation.

Nieznany
  • 79
  • 2
0

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;
    }
}
Sai Puli
  • 951
  • 8
  • 12