#45 This and Super Method in Java | Skyhighes | Lecture 45

11 months ago
14

Here's a comprehensive explanation of the this and super keywords in Java, focusing on their use within methods:

this Keyword

Within a method, this refers to the current object—the object whose method is being called. It has several uses:

Referencing instance variables: To distinguish between local variables and instance variables with the same name:
Java
public class Person {
private String name;

public void setName(String name) {
this.name = name; // Refers to the instance variable
}
}
Use code with caution. Learn more
Calling other methods of the same object: To invoke another method of the current object:
Java
public class Person {
public void introduce() {
System.out.println("Hello, my name is " + this.getName());
}
}
Use code with caution. Learn more
Passing the current object as an argument: To pass the current object as a reference to another method:
Java
public class Person {
public void register(Event event) {
event.addParticipant(this); // Passing the current Person object
}
}
Use code with caution. Learn more
super Keyword

Within a method, super refers to the immediate parent class of the current object. It's primarily used to:

Access superclass members: To access members (variables or methods) of the superclass that have been hidden or overridden:
Java
public class Employee extends Person {
public String getDetails() {
return super.getName() + ", works in IT"; // Accessing superclass method
}
}
Use code with caution. Learn more
Call superclass constructors: To explicitly call a constructor of the superclass from a subclass constructor:
Java
public class Employee extends Person {
public Employee(String name, String jobTitle) {
super(name); // Calling superclass constructor
this.jobTitle = jobTitle;
}
}
Use code with caution. Learn more
Key Points:

this and super are both reserved keywords in Java.
They are used within methods to refer to different objects within the inheritance hierarchy.
this is used for accessing or calling members of the current object.
super is used for accessing or calling members of the superclass.
Understanding these keywords is essential for working with inheritance and object relationships in Java.

Loading comments...