Conversation with Merlin [email protected] · Wed Jan 10 2024

java code for abstraction

Certainly! Abstraction in Java is achieved using abstract classes and. Here's an example of each:

  1. Abstract Class:

java abstract class Shape { abstract void draw(); }

class Circle extends Shape { void draw() { System.out.println("Drawing Circle"); } }

class Rectangle extends Shape { void draw() { System.out.println("Drawing Rectangle"); } }

public class Main { public static void main(String[] args) { Shape circle = new Circle(); Shape rectangle = new Rectangle(); circle.draw(); rectangle.draw(); } }

2. Interface: ```java interface Shape { void draw(); } class Circle implements Shape { public void draw() { System.out.println("Drawing Circle"); } } class Rectangle implements Shape { public void draw() { System.out.println("Drawing Rectangle"); } } public class Main { public static void main(String[] args) { Shape circle = new Circle(); Shape rectangle = new Rectangle(); circle.draw(); rectangle.draw(); } }

In both examples, theShapeclass or interface is abstract and contains an abstract methoddraw(). The concrete classes CircleandRectangleprovide a specific implementation of thedraw()method. This allows for abstraction, as you can refer to the objects using the abstract typeShape` without needing to know the specific implementation.