Final variables in Java

 

🔷 Final Variables in Java

✅ What is final in Java?

The final keyword is used to declare constants. Once assigned, a final variable's value cannot be changed.


📌 Types of Final Usage:

  1. Final variable

  2. Final method

  3. Final class


✅ 2.1 Final Variable

  • Value is assigned only once.

  • If not initialized during declaration, it must be initialized in a constructor or static block.

🔹 Example:


class Circle { final double PI = 3.14159; // constant double area(double r) { return PI * r * r; } }

✅ 2.2 Final Method

  • Cannot be overridden by subclasses.


class A { final void show() { System.out.println("This is a final method."); } } class B extends A { // void show() {} ❌ Compilation error }

✅ 2.3 Final Class

  • Cannot be extended (no subclassing).


final class Animal { void sound() { System.out.println("Animal sound"); } } // class Dog extends Animal {} ❌ Error: Cannot inherit from final class

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine