+91 81900 98289

Java Abstract Class

An abstract class can hold shared code and can declare abstract methods that have no body. A subclass must implement those methods, or it must be abstract too. You cannot write new on the abstract class itself.

Use an abstract class when several related classes share fields and some real methods, and each one must fill in one missing action.

Example

Box supplies the missing method. The call through the Shape variable runs Box.sides.

abstract class Shape { abstract int sides(); } class Box extends Shape { @Override int sides() { return 4; } } public class Shapes { public static void main(String[] args) { Shape s = new Box(); System.out.println(s.sides()); } }
new Shape() does not compile. new Box() does, and a Shape variable may point at that box.