Abstract Class in Java

Abstract Class in Java provides a mechanism by which we can just define the definition of the method in class and not implement it. Any Class that extends the Abstract class has to implement the abstract methods.
Although Interface in Java provides the similar mechanism, but Interface provides total abstraction in a way that all the methods that are defined in an Interface are just definition.

Let’s see an Example of Abstraction to get the better understanding.

public abstract class Animal {
    
    String name;
    
    abstract void greet();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    

}

We have created an abstract class Animal. That contains a variable called name, an abstract method greet() and two general methods as setter and getter for field name.
As you can see as opposed to Interface , abstract Class in Java can contain general methods and abstract methods (methods without implementation). Any Class that extends this abstract class will have its own implementation for greet() method. Let’s create two classes Dog and Cat that extends this Animal Class.

public class Dog extends Animal{

    @Override
    void greet() {
        System.out.println("BOW! BOW!");  
    }

}
public class Cat extends Animal{

    @Override
    void greet() {
        System.out.println("Meow! Meow!");
    }

}

The Dog and Cat has their own implementation for the greet() method. And that’s how we achieve abstraction in Java. Let’s create a Main Class to see these classes in action.

public class Main {

    public static void main(String args[]) {
        Animal animal = new Dog();
        animal.setName("Tommy");
        System.out.println("Animal name is " + animal.getName());
        animal.greet();
        animal = new Cat();
        animal.setName("Lusy");
        System.out.println("Animal name is " + animal.getName());
        animal.greet();

    }

}

Output will be

Animal name is Tommy
BOW! BOW!
Animal name is Lusy
Meow! Meow!

Related Articles

If you like our content, please consider buying me a coffee.

Thank you for your support!

Buy me a coffeeBuy me a coffee

Leave a reply:

Your email address will not be published.

Site Footer