Fundamentals of Java
Super and This keywords of Java
Super Keyword:
Definition
: super is a reference to the immediate parent class of the current object. It is mainly used in the context of inheritance.
Usage
:
- Call the parent class's constructor: super() can be used to call the constructor of the parent class. This is often used to initialize inherited fields. 2.Access parent class methods: If a method in the subclass overrides a method in the parent class, super can be used to call the parent class’s version of the method.
- Access parent class fields: super can be used to access fields in the parent class if they are hidden by fields in the subclass.
1//super keyword is used to access the super class constructor.
2class Rectangle {
3 int length;
4 int breadth;
5 int x = 10;
6
7 Rectangle(int length, int breadth) {
8 this.length = length;
9 this.breadth = breadth;
10
11 }
12
13}
14
15class Cuboid extends Rectangle {
16 int height;
17 int x = 20;
18
19 Cuboid(int l, int b, int h) {
20 super(l, b);
21 height = h;
22 }
23
24 void display() {
25 System.out.println(super.x);
26 System.out.println(x);
27 System.out.println(this.x);
28
29 }
30
31 public static void main(String args[]) {
32 Cuboid c1 = new Cuboid(10, 20, 30);
33 c1.display();
34
35 }
36}
This Keyword:
Definition
: this is a reference to the current object whose method or constructor is being called.
Usage
:
- Access instance variables: When a parameter or local variable has the same name as an instance variable, this is used to distinguish between them.
- Call another constructor in the same class: this() can be used to invoke another constructor within the same class.
- Pass the current object as a parameter: You can pass this as an argument to another method.
1class Reactangle {
2 int length;
3 int breadth;
4
5 Reactangle(int length, int breadth) {
6 this.length = length;// if we will take the name of parameter variables same as our class variables
7 // then there will be a problem since if we write length=length, it means we're
8 // assigning the value to itself only and no value is assigned to our class
9 // variable to avoid this we use this keyword which indicates to the class
10 // variable while comparing it with parameterized variable.(this keyword is used to avoid the name conflict.)
11 this.breadth = breadth;
12
13 }
14
15 void display() {
16 System.out.println("length:" + this.length);
17 System.out.println("breadth:" + this.breadth);
18 }
19
20 public static void main(String[] args) {
21 Reactangle r1 = new Reactangle(2, 5);
22 Reactangle r2 = new Reactangle(3, 4);
23 r1.display();
24 r2.display();
25 }
26}
Key Differences
:
- this refers to the current object, whereas super refers to the immediate parent class.
- this() is used to call a constructor in the same class, while super() calls the constructor of the parent class.
- this can only be used in non-static methods or constructors, while super can also be used similarly in instance methods or constructors.