What is "abstraction" in OOP
Abstraction is a way to highlight a set of general characteristics of an object, excluding private and insignificant ones from consideration. Accordingly, abstraction is a collection of all such characteristics.
Imagine that a driver is driving through a busy traffic area. It is clear that at this moment he will not think about the chemical composition of the paint of the car, the peculiarities of the interaction of the gears in the gearbox or the influence of the body shape on the speed (unless the car is in a dead traffic jam and the driver has absolutely nothing to do). However, he will use the steering wheel, pedals, turn signal regularly.
Example:
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}
}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}
}
class MyMainClass {
public static void main (String [] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
Read also:
Comments
Post a Comment