this and super keyword in Java

 

this and super keyword in java

this keyword 

  • In Java programming, the this keyword is a reference variable that refers to the current instance of the class. 
  • It can be used in various contexts within a class to differentiate between instance variables (class fields) and local variables with the same name, or to pass the current instance as an argument to another method.
  • Using "this" reference can improve code readability and reduce naming conflicts.
  • this keyword  helps avoid ambiguity when there's a local variable with the same name as an instance variable.


Here are some common uses of the this keyword in Java:

  1. Using the ‘this’ keyword to refer to instance variables of current class .
  2. Using this() to invoke the current class constructor.
  3. Using ‘this’ keyword to return the current class instance .
  4. Using ‘this’ keyword as the method parameter.
  5. Using ‘this’ keyword to invoke the current class method .
  6. Using ‘this’ keyword as an argument in the constructor call .



super keyword 

Here are the key points about the super keyword in Java:

1. Usage: 

  • The super keyword is used to refer to the immediate parent class of the current class, i.e., the superclass. 
  • It is primarily used in the context of inheritance to access members (fields and methods) of the parent class.


2. Accessing Parent Class Members: 

  • When a subclass extends a superclass, it inherits all the accessible non-private members of the superclass.
  • If the subclass wants to access or call a method or field that is overridden or hidden by the subclass, it can use the super keyword to access the superclass version of that member.


3.Constructor Chaining : 

  • When a subclass constructor is invoked, it implicitly calls the constructor of its superclass before executing its own constructor code. This process is called "constructor chaining." 
  • The super() method is used to call the superclass constructor explicitly. It must be the first statement in the subclass constructor.


4. Preventing Ambiguity: 

  • In situations where both the superclass and subclass have members with the same name (method or field), using super explicitly clarifies that you want to refer to the parent class's member.


5. Inheritance of Constructors: 

  • Constructors are not inherited, but they are called in the constructor chaining process. 
  • The subclass constructor must call one of the superclass constructors using super() before performing its own initialization.


6. Static Context: 

  • The super keyword cannot be used in a static context (i.e., in a static method or block) because it refers to an instance of the superclass, and static methods are not associated with instances.


Ex : Super_keyword.java



Comments

Popular Posts