Java Constructor variables being ignored

前端 未结 7 1101
我在风中等你
我在风中等你 2021-01-27 05:54

I am trying to create a instance of the object Iset. When the person makes the object they have to give an int which will be the size of a boolean array that will store a set of

7条回答
  •  甜味超标
    2021-01-27 06:28

    Lets have a look at your code :

     public class Iset {
        public int size;// Declares a Member of a class and all the objects will have a copy of this member
        boolean[] Iset;
    .....
    }
    
    
        ISet(int a) {
            int size = a; //This line is declaring a **local variable** called size 
            seti = new boolean[size];
    ...
    }
    

    See in your constructor you've created a local variable size but you also have a class member called size in your class. So in this scenario whenever we try to set size variable within constructor, there arises a conflict to the compiler whether to set the local variable or the class member ( this conflict is because of the fact that both the local variable and class member has same name ) . In such scenarios the compiler chooses local variable size over the class member size. But for you to make sure that the values you use in the constructor are used in all of my methods, you have to set the class member. To set the class member we use following code:

    this.size = a;//Says set the object member size to value present in a.
    

    Here we refer the size using this pointer because we need to set the object's size variable and not the local variable size.

提交回复
热议问题