Abstraction
Abstraction is a process of hiding the implementation details and showing only the functionality to the user. It helps in reducing complexity and allows focusing on what an object does instead of how it does it.
How Abstraction Works
Abstraction is implemented using abstract classes and interfaces:
abstract class Animal {
// Abstract method
public abstract void makeSound();
// Regular method
public void sleep() {
System.out.println("Sleeping");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Outputs: Bark
myDog.sleep(); // Outputs: Sleeping
}
}
In this example, Animal
is an abstract class with an abstract method makeSound
. The Dog
class extends Animal
and provides the implementation for the makeSound
method.
Interfaces
An interface is another way to achieve abstraction in Java:
interface Animal {
public void makeSound();
}
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Cat myCat = new Cat();
myCat.makeSound(); // Outputs: Meow
}
}
In this example, Animal
is an interface with a method makeSound
. The Cat
class implements the Animal
interface and provides the implementation for the makeSound
method.
Continue exploring our intermediate tutorials to learn more about Java programming.