Understand abstract keyword in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 18 August 2019   |   Print Email
This article helps you understand what is abstract keyword in Java and how to use it in the Java programming language.
You know, the abstract keyword is used to declare a class or a method as abstract. An abstract class can have abstract methods which have to be implemented by its sub classes. An abstract method does not have concrete implementation or body, and must ends with a semicolon. The following example declares a class Car as abstract:
public abstract class Car { public abstract void drive(); }
The method drive() is also declared as abstract.
1. Some rules for abstract class and abstract method:
An abstract class:
- cannot be instantiated by the new keyword. The purpose of an abstract class is to be inherited by derived classes.
- can have both abstract and non-abstract methods.
An abstract method:
- does not have body and must end with a semicolon.
- must be implemented by concrete sub classes.
- makes the enclosing class must be declared as abstract also
2. Java abstract class and method example
A class that extends the abstract Car class and implements its abstract method:
class PoliceCar extends Car { public void drive() { // drive faster than normal car } }
An abstract class has both abstract and non-abstract methods:
abstract class Airplane { public abstract void takeOff(); public void landing() { // landing smoothly } }
See all keywords in Java.
Related Topics:
- Understand abstraction in Java OOP
- Learn access modifiers in Java
- Understand default methods in Java
- How to use final keyword in Java
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
It means creating a new object.