Abstraction in java with example

Abstraction in java with example

Abstraction in Java is a fundamental object-oriented programming concept that focuses on hiding complex implementation details and exposing only the necessary features of an object. This allows programmers to work with objects at a higher level without needing to understand all the intricacies of their implementation.

Example using Abstract Classes

An abstract class can have abstract methods (without a body) as well as concrete methods (with a body). Here’s an example:

Example
// Abstract class
abstract class Animal {
    // Abstract method (does not have a body)
    abstract void makeSound();

    // Concrete method
    void sleep() {
        System.out.println("Sleeping...");
    }
}

// Subclass (inheriting from Animal)
class Dog extends Animal {
    // Implementing the abstract method
    void makeSound() {
        System.out.println("Woof!");
    }
}

// Subclass (inheriting from Animal)
class Cat extends Animal {
    // Implementing the abstract method
    void makeSound() {
        System.out.println("Meow!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        Animal myCat = new Cat();
        
        myDog.makeSound(); // Outputs: Woof!
        myCat.makeSound(); // Outputs: Meow!
        
        myDog.sleep();     // Outputs: Sleeping...
        myCat.sleep();     // Outputs: Sleeping...
    }
}

Abstraction in java with example

Home Page

reference