Home > OS >  What is the difference in object assignment that is done within a method of class and within the sam
What is the difference in object assignment that is done within a method of class and within the sam

Time:07-10

class A {
   
   B objB1; 
 
   public A() {
       objB1 = new B();
   }
   
   B objB2 = objB1; // location 1
       
   public void aMethod() {
       B objB2 = objB1; // location 2
   }
     
   class B{
       // class def
   }
}

This is probably a java core question. But what is the difference in object assignment in location 1 and location 2? What will happen if I use object from location 1 (after commenting out location 2) within aMethod() ?

CodePudding user response:

Reference assignment, not instantiation

As commented, neither location 1 nor location 2 involves instantiation. Both assign an object reference to a reference variable (notably, two different reference variables).

So the title of your Question makes no sense.

Variable Shadowing

Furthermore, you have a problem with variable shadowing. In aMethod you declared a local variable with the same name as the class member variable: objB2. Both of these can hold a reference to an object of type B.

When the method aMethod exits, its locally declared variable objB2 is cleared from the stack, eliminated from memory. Meanwhile, the member field variable objB2 continues to exist.

CodePudding user response:

the object in location 1 is global variable.

in location 2 the object "objB2" is local variable in method and if you want to Access to the object defined in the location 1 (from the method "aMethod") you need to write this.objB2.

  • Related