Great question ....
π§ Can We Create an Object of an Abstract Class?
No, you cannot directly create an object of an abstract class in Java.
Abstract classes are incomplete by design—they may contain abstract methods (without implementation), which means they are meant to be extended by subclasses that provide concrete implementations.
✅ What You Can Do Instead
You can:
- Create a reference of the abstract class type, and assign it an instance of a concrete subclass.
- Use anonymous inner classes to instantiate an abstract class with method implementations on the fly.
π Example 1: Using a Concrete Subclass
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Woof!");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // ✅ Valid
myDog.makeSound(); // Output: Woof!
}
}
π Example 2: Anonymous Inner Class
abstract class Greeting {
abstract void sayHello();
}
public class Main {
public static void main(String[] args) {
Greeting g = new Greeting() {
void sayHello() {
System.out.println("Hello from anonymous class!");
}
};
g.sayHello(); // Output: Hello from anonymous class!
}
}
Also, refer below in detail to make it understand well.
Even if an abstract class has no abstract methods, you still cannot create an object of it directly.
π Why?
Declaring a class as abstract tells the compiler:
“This class is incomplete and not meant to be instantiated directly.”
Even if all methods are implemented, the abstract keyword blocks object creation.
✅ What You Can Do
You can:
- Extend the abstract class in a concrete subclass.
- Create an object of the subclass, which inherits the behavior.
π§ͺ Example
abstract class Base {
void show() {
System.out.println("Hello from Base");
}
}
// ❌ This will cause a compilation error:
// Base b = new Base();
class Derived extends Base {
// Inherits show()
}
public class Main {
public static void main(String[] args) {
Base b = new Derived(); // ✅ Valid
b.show(); // Output: Hello from Base
}
}
No comments:
Post a Comment