Abstraction is a process of hiding the implementation details and showing only the essential features of an object. It focuses on what an object does rather than how it does it. Abstraction in Java is achieved through abstract classes and interfaces.
abstract
keyword.abstract class Animal {
abstract void sound(); // Abstract method (no body)
void eat() { // Concrete method
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
= new Dog();
Dog myDog .sound();
myDog.eat();
myDog}
}
interface
keyword.interface Animal {
void sound(); // Abstract method (implicitly public and abstract)
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
= new Dog();
Dog myDog .sound();
myDog}
}
interface Animal {
void sound();
default void sleep() {
System.out.println("This animal sleeps");
}
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
= new Dog();
Dog myDog .sound();
myDog.sleep();
myDog}
}
Feature | Abstract Class | Interface |
---|---|---|
Keyword | abstract |
interface |
Inheritance | Can extend one class (abstract or concrete) | Can implement multiple interfaces |
Methods | Can have both abstract and concrete methods | Only abstract methods (Java 7 and below) |
Fields | Can have instance variables | Only static and final variables |
Constructor | Can have constructors | Cannot have constructors |
Usage | For classes with shared code and abstract behavior | For providing a contract for other classes |
Abstraction is a crucial concept in Java, promoting the separation of the interface from the implementation. It allows developers to focus on high-level design and functionality, improving code manageability and scalability.