What is this in Java?
The this keyword in Java refers to the current object of the class. It helps differentiate between instance variables and parameters or call methods/constructors within the same class.
When do we use this?
When local variables and instance variables have the same name.
To call another constructor in the same class.
How is this used?
To refer to the current object variable.
To pass the current object as a parameter.
To call another constructor in the same class.
Why We use?
To remove confusion between local and instance variable
Program:
class Student {
int Rollno;
String Name;
int Age;
Student(int Rollno, String Name, int Age) {
this.Rollno = Rollno;
this.Name = Name;
this.Age = Age;
}
void display() {
System.out.println(Rollno + " " + Name + " " + Age);
}
}
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student(101, "Arun",24);
s1.display();
}
}
Output:
101 Arun 24
What is super in Java?
The super keyword in Java is used to refer to the immediate parent class object. It comes in handy when working with inheritance.
When do we use super?
When you want to call the parent class constructor.
When a child class overrides a method but you still need the parent class version.
To access parent class variables when they are hidden by child class variables.
How is super used?
To call the parent class constructor.
To access parent class variables.
To access parent class methods.
Why We use?
We use the super keyword in java to access parent class variable and methods
Program:
class Animal {
void show() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
void show() {
super.show();
System.out.println("dog is barking");
}
}
public class TestName {
public static void main(String args[]) {
Dog d1 = new Dog();
d1.show();
}
}
Output:
Animal sound
dog is barking
Top comments (0)