Java Keywords
Java Keywords
Java Keywords:
this, super, and
final
By
Vansh Aggarwal
Btech cse 5th sem
211261015025
1. this Keyword :
• “this” keyword refers to the current object
inside a method or constructor.
class A A@5acf9800
{
obj A
}
this
A obj = new
A();
class A{
void show()
{
System.out.println(this);
}
public static void main(String[] args) {
A obj = new A();
System.out.println(obj);
obj.show();
}
}
Output:
A@5acf9800
A@5acf9800
• The keyword ‘this’ refers to the current instance of
the class and can be used to refer to the instance
variables of the class. It is particularly useful when
there is a need to distinguish between instance
variables and local variables that share the same
name within a method or constructor.
public class A {
int x;
1.
• To refer immediate parent class
instance variable.
2.
• To invoke immediate parent class
method.
3.
• To invoke immediate parent class
constructor.
Example program
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal
class
}
}
class Main{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
3. final keyword :
• The final keyword can be used to indicate that
something cannot be changed.
• Once any data member gets declared as final, it can
only be assigned once.
Final
Stop
Helps to create Prevent from
inheritance by
constant variables method overriding
any child class
class Bike{ class Bike{
final void run(){
final int speedlimit=90;//final
variable System.out.println("running");}
void run(){ }
speedlimit=400;
} class Honda extends Bike{
void run()
public static void main(String {System.out.println("running wit
args[]){ h 100kmph");
Bike9 obj=new Bike(); }
obj.run();
} public static void main(String arg
} s[]){
Honda honda= new Honda();
honda.run();
THANK YOU