[Go to site: main page, start]

0% found this document useful (0 votes)
28 views1 page

Java Abstract Class Interview Guide

In Java, a class can be declared abstract if it contains abstract methods, and it can also be abstract without any abstract methods to prevent instantiation. Subclasses of an abstract class must implement its abstract methods. An abstract class serves as a blueprint for creating specific implementations, like defining a 'Vehicle' class for specific vehicles such as 'Car' or 'Bike'.

Uploaded by

Jana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views1 page

Java Abstract Class Interview Guide

In Java, a class can be declared abstract if it contains abstract methods, and it can also be abstract without any abstract methods to prevent instantiation. Subclasses of an abstract class must implement its abstract methods. An abstract class serves as a blueprint for creating specific implementations, like defining a 'Vehicle' class for specific vehicles such as 'Car' or 'Bike'.

Uploaded by

Jana
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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'.

You might also like