this Keyword in Java

The this keyword in Java is a reference variable that refers to the current object of a class. It is commonly used to distinguish instance variables from local variables when they have the same name.

  • Refers to the current class object.
  • Used to access current class instance variables and methods.
  • Used to invoke another constructor of the same class using this().

Example

`class Student {
String name;
int age;

Student(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println(this.name); System.out.println(this.age); } 

}`

public class Main {
public static void main(String[] args) {
Student s1 = new Student("Gowtham", 20);
s1.display();
}
}

Output:

Gowtham
20

Explanation

  • this.name refers to the instance variable.
  • name refers to the constructor parameter.
  • this.age refers to the instance variable.
  • age refers to the constructor parameter.
  • The this keyword helps us avoid confusion when variable names are the same.

Common Uses of this Keyword

  1. Referring to current class instance variables.
  2. Calling another constructor using this().
  3. Calling a method of the current object.
  4. Passing the current object as an argument.

final Keyword in Java

In Java, the final keyword is used to restrict changes and make code more secure and predictable. It can be applied to variables, methods, and classes to prevent modification, overriding, or inheritance. This helps in creating constant values, stable methods, and immutable classes.

1. Final Variable

A final variable cannot be reassigned after it has been initialized.

Example:

`public class Main {
public static void main(String[] args) {
final int age = 20;

 System.out.println(age); } 

}`

Output:

20

Here, age is a final variable, so we cannot assign another value to it.

2. Final Method

A final method cannot be overridden by a subclass.

Example:

`class Parent {
final void display() {
System.out.println("This is a final method");
}
}

class Child extends Parent {
// Cannot override display()
}`

public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}

Output:

This is a final method

Here, the display() method is declared as final, so the child class cannot override it.

3. Final Class

A final class cannot be extended by another class.

Example:

final class Student {
void display() {
System.out.println("Hello Java!");
}
}

public class Main {
public static void main(String[] args) {
Student s1 = new Student();
s1.display();
}
}

Output:

Hello Java!

Here, Student is a final class, so another class cannot inherit from it.