Back to: Java Tutorials
An abstract class is a class that cannot be instantiated and can only be used as a superclass for other classes. Abstract classes can contain both abstract and non-abstract methods, as well as instance variables. In this tutorial, we will provide an example of how to create and use an abstract class in Java.
Creating an Abstract Class in Java
To create an abstract class in Java, you need to use the abstract
keyword in the class declaration. Here is an example of an abstract class:
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void makeSound();
}
In this example, we have created an abstract class called Animal
. The Animal
class has an instance variable called name
and a constructor that takes a name parameter. It also has a getName
method that returns the name of the animal.
The Animal
class also has an abstract method called makeSound
. Abstract methods are defined using the abstract
keyword and do not have an implementation. Any class that extends the Animal
class must provide an implementation for the makeSound
method.
Using an Abstract Class in Java
To use an abstract class in Java, you need to create a subclass that extends the abstract class and provides an implementation for any abstract methods. Here is an example of a subclass that extends the Animal
class:
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void makeSound() {
System.out.println("Woof!");
}
}
In this example, we have created a subclass of the Animal
class called Dog
. The Dog
class has a constructor that takes a name parameter and passes it to the Animal
constructor using the super
keyword.
The Dog
class also provides an implementation for the makeSound
method, which prints “Woof!” to the console.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author