What is Abstraction?
Abstraction is one of the key principles of object-oriented programming (OOP). It is a concept that allows you to model real-world entities by simplifying their complexities. Abstraction involves focusing on the essential features of an object while ignoring the non-essential details.
In Java, abstraction is achieved through abstract classes and interfaces.
1. Abstract Classes:
Syntax
abstract class Shape {
abstract void draw(); // Abstract method
void display() {
// code;
}
}
Example
// Abstract class
abstract class Shape {
abstract void draw();
void display() {
System.out.println("Displaying shape");
}
}
class Circle extends Shape {
// Implementing the abstract method
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
// Implementing the abstract method
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw(); // Calls the overridden draw method in Circle
circle.display(); // Calls the inherited display method from Shape
Rectangle rectangle = new Rectangle();
rectangle.draw(); // Calls the overridden draw method in Rectangle
rectangle.display(); // Calls the inherited display method from Shape
}
}
2. Interfaces:
Syntax
interface Shape {
void draw(); // Abstract method
void resize(); // Another abstract method
}
Example
// Interface
interface Shape {
// Abstract method (to be implemented by classes)
void draw();
}
class Circle implements Shape {
// Implementing the draw method from the Shape interface
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
// Concrete class implementing the Shape interface
class Rectangle implements Shape {
// Implementing the draw method from the Shape interface
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
// Main class to demonstrate the interface and its implementations
public class Main {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw(); // Calls the overridden draw method in Circle
Rectangle rectangle = new Rectangle();
rectangle.draw(); // Calls the overridden draw method in Rectangle
}
}
What are Abstract Methods?
Example
abstract class Shape {
abstract void draw(); // Abstract method
}
Abstract Class vs. Interface:
Example
interface Shape {
void draw(); // Abstract method
}
abstract class AbstractShape implements Shape {
void display() {
System.out.println("Displaying shape");
}
}
class Circle extends AbstractShape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
class Main {
public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
circle.display();
}
}
Note:- In above example, ‘Circle’ implements the abstract method ‘draw’ from the ‘Shape’ interface and inherits the display method from the abstract class 'AbstractShape'