What is Abstract on OOPS ?
Ans: Java mein abstract class ka use karke aap ek class ko define kar sakte hain jiska object directly create nahi kiya ja sakta, lekin jise aap dusre classes ke liye blueprint ke roop mein istemal kar sakte hain. Yeh abstract classes inheritance ke through ek hierarchy ko define karne mein bhi madad karte hain. Niche ek simple example diya gaya hai:
// Abstract class
abstract class Shape {
// Abstract method
abstract void draw();
// Non-abstract method
void display() {
System.out.println("This is a shape.");
}
}
// Concrete class extending abstract class
class Circle extends Shape {
// Implementing abstract method
void draw() {
System.out.println("Drawing a circle");
}
}
// Concrete class extending abstract class
class Rectangle extends Shape {
// Implementing abstract method
void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle();
circle.draw(); // Output: Drawing a circle
circle.display(); // Output: This is a shape.
Shape rectangle = new Rectangle();
rectangle.draw(); // Output: Drawing a rectangle
rectangle.display(); // Output: This is a shape.
}
}
Comments
Post a Comment