Mark As Completed Discussion

Abstraction

In object-oriented programming, abstraction is a key concept that allows us to simplify complex systems by focusing on the essential features and ignoring unnecessary details. It provides a way to represent real-world objects and their interactions in a simplified and logical manner.

Abstraction helps in managing the complexity of large systems by dividing them into smaller and manageable modules. These modules can be understood and developed independently, and their internal workings can be hidden from other modules, resulting in a more organized and maintainable codebase.

One way to achieve abstraction in Java is through the use of abstract classes and interfaces. An abstract class is a class that cannot be instantiated and serves as a blueprint for other classes. It may contain both abstract and non-abstract methods. Abstract methods are declared without an implementation and need to be overridden by the concrete subclasses.

For example, let's consider an abstract class Animal that represents a generic animal. The class has an abstract method makeSound() which is meant to be implemented by its subclasses. The class also has a non-abstract method sleep() which provides a common behavior for all animals:

TEXT/X-JAVA
1public abstract class Animal {
2    private String name;
3
4    public Animal(String name) {
5        this.name = name;
6    }
7
8    public abstract void makeSound();
9
10    public void sleep() {
11        System.out.println(name + " is sleeping.");
12    }
13}

We can then create a concrete subclass Dog which extends the Animal class and implements the makeSound() method:

TEXT/X-JAVA
1public class Dog extends Animal {
2    public Dog(String name) {
3        super(name);
4    }
5
6    @Override
7    public void makeSound() {
8        System.out.println("Woof woof!");
9    }
10}

In the Main class, we can create an instance of the Dog class and invoke the makeSound() and sleep() methods:

TEXT/X-JAVA
1public class Main {
2    public static void main(String[] args) {
3        Dog dog = new Dog("Rex");
4        dog.makeSound();
5        dog.sleep();
6    }
7}

When we run the above code, it will display the following output:

SNIPPET
1Woof woof!
2Rex is sleeping.
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment