java code for abstraction
Certainly! Abstraction in Java is achieved using abstract classes and. Here's an example of each:
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 method
draw(). The concrete classes
Circleand
Rectangleprovide a specific implementation of the
draw()method. This allows for abstraction, as you can refer to the objects using the abstract type
Shape` without needing to know the specific implementation.