this keyword
1.What is this?
this is a refers to the current object of a class.
2.Why use this?
To avoid confusion between instance variables and parameters.
To call other constructors in the same class.
To pass the current object as an argument.
To return the current object.
To access current class members (fields, methods) inside the class.
3.When to use this?
When method or constructor parameters shadow instance variables.
When chaining constructors using this().
When returning the current object from a method.
- Where is this used?
Inside non-static methods and constructors of a class.
Cannot be used in static context (like static methods) because this refers to an object, and static context belongs to class.
5.How to use this?
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id; // 'this' differentiates between field and parameter
this.name = name;
}
void display() {
System.out.println(this.id + " " + this.name); // refers to current object
}
Student getStudent() {
return this; // returns current object
}
}
super Keyword
1.What is super?
super is a reference variable used to refer to immediate parent class object.
- Why use super?
To access parent class:
Constructors
Methods
Fields
To avoid method or variable shadowing.
To call overridden methods from parent class.
3.When to use super?
When subclass overrides a parent method but still wants to call the original version.
When you want to access a parent variable that’s hidden by a child variable.
When subclass constructor must call parent class constructor explicitly.
- Where is super used?
Inside subclass constructors and methods.
Can’t be used in static context.
Must be the first statement in a constructor if used to call a parent constructor.
5.How to use super?
class Animal {
String color = "Brown";
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
String color = "Black";
void printColor() {
System.out.println(super.color); // access parent class variable
}
void sound() {
super.sound(); // call parent class method
System.out.println("Dog barks");
}
}
Top comments (1)
nice