What is the difference between final and abstract in Java?

The Difference Between final and abstract in Java

In Java, final and abstract are two distinct keywords that serve different purposes in the language. Understanding the differences between these two concepts is crucial for Java developers.

final Keyword

The final keyword in Java is used to create constants, prevent method overriding, and prevent class inheritance. When a variable is declared as final, its value cannot be changed after it has been initialized. This makes the variable a constant, and it is often used to define values that should remain unchanged throughout the program's execution.

Here's an example of using the final keyword to create a constant:

public class MyClass {
    public static final double PI = 3.14159;

    public static void main(String[] args) {
        System.out.println("The value of PI is: " + PI);
    }
}

In this example, PI is a final variable, and its value cannot be changed once it has been set to 3.14159.

The final keyword can also be used to prevent method overriding in subclasses. When a method is declared as final, it cannot be overridden in any subclasses. This is often used to ensure that a specific method behaves in a certain way and cannot be modified by subclasses.

Finally, the final keyword can be used to prevent a class from being extended (inherited). When a class is declared as final, it cannot be subclassed, and no other class can inherit from it.

classDiagram class FinalClass { <> } FinalClass --|> OtherClass : Cannot Inherit

abstract Keyword

The abstract keyword in Java is used to create abstract classes and abstract methods. An abstract class is a class that cannot be instantiated, and it is often used as a base class for other classes. Abstract classes can contain both abstract and non-abstract (concrete) methods.

Here's an example of an abstract class:

public abstract class Animal {
    public abstract void makeSound();

    public void eat() {
        System.out.println("The animal is eating.");
    }
}

In this example, the Animal class is an abstract class, and it contains an abstract method makeSound() and a concrete method eat(). Subclasses of Animal must provide an implementation for the makeSound() method.

Abstract methods are methods that have no implementation, and they must be overridden by any non-abstract subclasses. Abstract classes can also contain concrete methods, which can be inherited by subclasses.

classDiagram class AbstractClass { <> +makeSound() +eat() } class ConcreteClass { +makeSound() } AbstractClass <|-- ConcreteClass : Implements Abstract Methods

In summary, the final keyword is used to create constants, prevent method overriding, and prevent class inheritance, while the abstract keyword is used to create abstract classes and abstract methods, which must be implemented by subclasses.

0 Comments

no data
Be the first to share your comment!