⬅ Previous Topic
Java Method OverridingNext Topic ⮕
Interfaces in Java⬅ Previous Topic
Java Method OverridingNext Topic ⮕
Interfaces in JavaAbstraction allows us to hide the complex implementation details and show only the essential features of an object. Think of it like the steering wheel of a car – you use it to drive, but you don’t need to understand how the engine works.
Abstraction helps in:
Java provides two main tools to achieve abstraction:
An abstract class is a class that cannot be instantiated directly. It can have both abstract methods (without a body) and concrete methods (with a body).
abstract class Animal {
abstract void sound(); // abstract method
void sleep() { // concrete method
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Outputs "Bark"
d.sleep(); // Outputs "Sleeping..."
}
}
Bark
Sleeping...
An interface is a 100% abstract type in Java. It can only contain abstract methods (until Java 7), and from Java 8 onwards, it can also contain default and static methods with implementations.
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car starting...");
}
public void stop() {
System.out.println("Car stopping...");
}
}
public class Main {
public static void main(String[] args) {
Car c = new Car();
c.start(); // Outputs "Car starting..."
c.stop(); // Outputs "Car stopping..."
}
}
Car starting...
Car stopping...
Feature | Abstract Class | Interface |
---|---|---|
Methods | Can have both abstract and concrete methods | Abstract methods only (until Java 7); default/static from Java 8 |
Multiple Inheritance | Not supported | Supported |
Access Modifiers | Can use any access modifier | All methods are public by default |
Constructor | Can have constructors | Cannot have constructors |
Imagine a remote control – it represents an interface. Every brand of TV has a different implementation (class), but the functions like power, volume, and channel are standardized. You press a button without knowing the circuit behind it.
By designing classes with abstract methods or interfaces, we enforce a contract that subclasses must fulfill, without worrying about their specific implementation details.
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Sleeping...");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.sleep();
}
}
⬅ Previous Topic
Java Method OverridingNext Topic ⮕
Interfaces in JavaYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.