What is the purpose of abstract classes in Java?

I have a few questions around abstract classes and their use. I know the basics about them; for example, that they cannot be created, they can have concrete and abstract methods ... But I think I want to know what purpose they fulfill in life (in software development)?

What is the purpose of abstract classes in Java? Why and when should an abstract class be used? If you can use a regular class and then inherit it, why would you inherit an abstract class? How will using abstract classes make our life easier? will it provide better maintainability? more flexibility? ...

btw, I already examined some similar questions and answers, including Understanding the purpose of abstract classes in Java , but they do not answer my question. I'm more looking for answers that shed light on the philosophy of introducing abstract classes primarily in Java.

thank

+4
source share
2 answers

A class abstractcan be used as a template type for other classes and is most often used for inheritance.

The best example from the first chapter of the java book:

abstract class Animal(){}

then you can expand the subclass, for example: dog, cat, fish.

+3
source

- , . - , , . . .

, , , Animal. , , , , . , -. -, ( ). , (, , ).

public abstract Animal {
public void eat(Food food) {
    // do something with food....
}
public void sleep(int hours) {
    try {
        // 1000 milliseconds * 60 seconds * 60 minutes * hours
        Thread.sleep(1000 * 60 * 60 * hours);
    } catch (InterruptedException ie) { /* ignore */
    }
}

public abstract void makeNoise();
}

, abstract , . , (, ), makeNoise - . Dog and Cow, Animal.

 public Dog extends Animal {
    public void makeNoise() {
        System.out.println("Bark! Bark!");
    }
}

public Cow extends Animal {
    public void makeNoise() {
        System.out.println("Moo! Moo!");
    }
}

, , . , - . , ( ) . - - .

+16

All Articles