this keyword in Java

   What problems to need this keyword in Java?

             
    
  1. It is illegal in Java Language to declare two variables with same name inside the same scopes.
  2. When the local variables and instance variables has same name then local variables hides the instance variables.




Solution of problems:


The this keyword lets us refer directly to the object we can use it to resolve any name-space collisions that occurs between local and instance variables.

  • In Java Language Java define the this keyword.
  • this keyword is used to resolve the name-space collisions.
  • The this keyword is used to inside any method to refer to the any object.
  • Sometimes a method need to refer to the object that invoked it. 
  • this keyword is always a reference to the object on which the method was invoked 

  


Use this keyword to resolve name-space collisions:

Box(double width, double height, double depth) {
                        this.width = width;
                        this.height = height;
                        this.depth = depth;
                        }


Comments

Popular posts from this blog

Inheritance in Java

Operators in Java Language?

Type Casting or Conversion in Java