0/30 Days Completed 0 Learning Days
Day 23 of 30 · Week 4 — OOPs Through Java
this and super keywords
1 Learn
this refers to the current object. It is often used when a parameter has the same name as a field: this.name = name.
super refers to the parent class. super(...) calls the parent constructor (as the first statement), and super.method() calls the parent's version of a method.
2 See the Code
Java
class Person {
String name;
Person(String name) {
this.name = name;
}
void intro() { System.out.println("I am " + name); }
}
class Teacher extends Person {
String subject;
Teacher(String name, String subject) {
super(name);
this.subject = subject;
}
@Override
void intro() {
super.intro();
System.out.println("I teach " + subject);
}
}
public class School {
public static void main(String[] args) {
new Teacher("Mr. Rao", "Java").intro();
}
}- this.name = name — the field gets the parameter's value.
- super(name) runs Person's constructor first.
- super.intro() reuses the parent's method, then adds more.
Output
I am Mr. Rao I teach Java
3 Practice
- Create Employee(name) and Manager(name, team) that uses super(name) and this.team = team.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. this refers to...
2. Where must super(...) appear in a constructor?
Step 5
Answer and check the Quick Check above to unlock this.