Abstraction is the concept of hiding the implementation details and showing only the necessary functionality to the user. In Java, abstraction can be achieved using abstract classes and interfaces.
abstract class Animal {
abstract void sound(); // Abstract method
void sleep() { // Regular method
System.out.println("This animal is sleeping.");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class AbstractionExample {
public static void main(String[] args) {
Animal myDog = new Dog(); // Creating an object of the subclass
myDog.sound();
myDog.sleep();
}
}
An abstract class can have both abstract (without implementation) and non-abstract (with implementation) methods. In this example, the sound() method is abstract and must be implemented by the subclass.
interface Animal {
void sound();
}
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
public class AbstractionExample {
public static void main(String[] args) {
Animal myDog = new Dog(); // Creating an object of the implementing class
myDog.sound();
}
}
Interfaces allow you to define methods that must be implemented by any class that implements the interface. The Dog class implements the Animal interface and provides its own implementation of the sound() method.