InterviewSolution
| 1. |
super vs this in Java |
|
Answer» Both super and this are keywords in JAVA. Details about these are GIVEN as follows: The super keywordThe super keyword is a reserved keyword in Java that is used to refer to the immediate parent class. The super keyword can also invoke the method and constructor of the immediate parent class. A program that demonstrates the super keyword is given as follows: class A { int x = 26; static int y = 15; } public class B EXTENDS A { void display() { System.out.println(super.x); System.out.println(super.y); } public static void main(String[] args) { B obj = new B(); obj.display(); } }The OUTPUT of the above program is as follows: 26 15The this keywordThe this keyword is a reserved keyword in Java that is used to refer to the current class instance variable. The this keyword can also invoke the method and constructor of the current class. It can also be passed as an argument in the method or constructor call. A program that demonstrates the super keyword is given as follows: public class Demo { int x = 25; static int y = 12; void display() { this.x = 250; System.out.println(x); this.y = 120; System.out.println(y); } public static void main(String[] args) { Demo obj = new Demo(); obj.display(); } }The output of the above program is as follows: 250 120 |
|