Java Interview Preparation
1. Can I declare a class with abstract?
Answer:
Yes. In Java, if a class has any abstract method, the class itself must be declared abstract. You can also declare a class
abstract even if it has no abstract methods. That?s often done to prevent instantiation while still providing some shared
implementation.
// 1. Invalid: won't compile
class Animal {
public abstract void makeSound(); // compile error
}
// 2. Valid abstract class
abstract class Animal {
public abstract void makeSound();
}
// 3. Abstract class with implemented method
abstract class UtilityBase {
public void helper() {
[Link]("Helping");
}
}
// 4. Subclass must implement abstract method
class Dog extends Animal {
@Override
public void makeSound() {
[Link]("Bark");
}
}
// Usage:
Animal a = new Dog(); // OK
// Animal a = new Animal(); // Compile error: cannot instantiate abstract class
Real-life Example:
An abstract class is like a blueprint. For example, you can define a 'Vehicle' with generic features, but to use it in real
life, you must build a specific vehicle like a 'Car' or 'Bike'.