Abstraction in Java is an OOP concept that focuses on hiding internal implementation details and showing only essential features to the user. It helps reduce complexity and increase maintainability.
An abstract class can have abstract and non-abstract methods. Abstract methods do not have a body and must be implemented by child classes.
// Abstract class defining common behavior
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Animal is sleeping");
}
}
// Child class providing implementation
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
// Main class to test abstraction
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
a.sleep();
}
}
Dog barks
Animal is sleeping
The reference variable of abstract type calls the implementation provided by the child class.
The code calls animal.sound(), but the implementation changes based on the object you create.
draw()