Creating Abstract Classes in Java Tutorial
Q: How do you create and use an abstract class in Java?
- Java
- Mid level question
Explore all the latest Java interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Java interview for FREE!
In Java, an abstract class is a class that cannot be instantiated, but can be subclassed. Abstract classes are used to provide a common interface for a group of related classes, and to define abstract methods that must be implemented by the subclasses.
Here are the basic steps for creating and using an abstract class in Java:
1. Declare the abstract class: To declare an abstract class in Java, you use the `abstract` keyword, followed by the class definition. For example:
public abstract class Animal { private String name; public Animal(String name) { this.name = name; } public String getName() { return name; } public abstract void makeSound(); }
This defines an abstract class called `Animal`. The class includes a constructor and a method called `getName()`, which are implemented by the class. The class also includes an abstract method called `makeSound()`, which is not implemented by the class.
2. Implement the abstract class: To implement an abstract class, you create a subclass that extends the abstract class and provides implementations for any abstract methods. For example:
public class Dog extends Animal { public Dog(String name) { super(name); } public void makeSound() { System.out.println("Woof!"); } }
This defines a class called `Dog` that extends the `Animal` abstract class. The class provides an implementation for the `makeSound()` method, which was declared as abstract in the `Animal` class.
3. Use the abstract class: Once you have defined an abstract class and implemented it in a subclass, you can use the abstract class to create objects of the subclass. For example:
Animal myAnimal = new Dog("Fido"); System.out.println("Name: " + myAnimal.getName()); myAnimal.makeSound();
In this example, we create a `Dog` object and assign it to a variable of type `Animal`. Because `Dog` extends the `Animal` abstract class, it can be treated as an `Animal` object. We then call the `getName()` and `makeSound()` methods on the `myAnimal` object, which call the implementations provided by the `Dog` class.
Note that an abstract class can have both abstract and non-abstract methods, and can also include instance variables and constructors. However, an abstract class cannot be instantiated directly, and any abstract methods must be implemented by any concrete subclasses.


