What is abstraction?
Abstraction is the abstraction of what is common and essential from more than one thing.
What is an abstract class
In the Java language, a class modified with the abstract keyword is called an abstract class. The class itself does not exist, so abstract classes cannot create objects cannot be instantiated.
In the object-oriented domain, abstract classes are mainly used for type hiding.
What are Abstract Methods
Methods in an abstract class that are modified with the keyword abstract are called abstract methods (only the declaration, not the method body)
Example:
public abstract class Car{ //abstract class
public abstract void start(); //abstract method
}
Benefits of Abstract Classes
-
Code can be reused
-
Use polymorphism to hide implementation class types and get more flexibility
Characteristics of Abstract Classes
- Abstract classes, whose modifiers must be public or protected, cannot be private, because to create an abstract class is to be inherited by other classes;
- Abstract classes cannot instantiate objects; they are instantiated through their ordinary subclasses;
- When a common class inherits an abstract class, that common class must override the abstract methods of the parent class;
- A class can be declared as an abstract class even if it does not include any abstract methods;
- Abstract classes can have no abstract methods in them; however, classes with abstract methods must be abstract.
Difference between abstract and concrete classes
Abstract classes have only method declarations, not method bodies (concrete implementations), so abstract classes cannot instantiate objects;
All methods of a concrete class contain method declarations and method bodies, so concrete classes can instantiate objects.
an actual example
abstract class Door {
public int weight;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
= weight;
}
public abstract void open();
public abstract void close();
}
class WoodenDoor extends Door{
public void open(){
("Opening wooden door");
}
public void close(){
("Closing wooden door");
}
}
class IronDoor extends Door{
public void open(){
("Opening iron door");
}
public void close(){
("Closing iron door");
}
}
public class Main{
public static void main(String[] args) {
Door door = new WoodenDoor();//upward type conversion(polymorphic)
();
();
(10);
(());
door = new IronDoor();
();
();
}
}