Java: Abstract classes and methods with example

In this article, we will learn about abstract classes and methods with detailed example

 

Abstract Class

A class with abstract keyword in class declaration is known as abstract class in Java. Unlike class, an abstract class can contain both abstract methods as well as concrete methods (i.e.; methods with braces and method body or method implementation)

Let us see simple example for abstract class with abstract method & concrete method

AbstractExample.java

An abstract class with both abstract & concrete methods and default no-arg constructor

Also, it can have both static and non-static (instance data member) fields but cannot be instantiated

package in.bench.resources.abstractclass.example;

// abstract class
public abstract class AbstractExample {

        // variables
	String demoString;
	static int demoCounter;

	// default no-arg constructor
	AbstractExample(){
		// do some initialization logic here
	}

	// abstract method declaration in abstract class
	abstract void myAbstractMethod();

	// concrete method definition in abstract class
	void myConcreteMethod() {
		System.out.println("AbstractExample: This is my concrete method in abstract class");
	}
}

 

Above abstract class contains

  • abstract method with no method body
  • concrete method with implementation
  • static int field
  • instance data member field of type String

If we try to instantiate an abstract class –> compiler throws compilation error stating reason

Compile-time error: Cannot instantiate the type AbstractExample

1_Abstract_class_instantiation_error

 

Abstract Method

A method declaration preceded/prefixed with abstract keyword with no body or no implementation detail which ends its method signature with semicolon(;)

Note: If required, an abstract method can throw any sort of exception from Exception hierarchy and overriding method must throw same or sub-type of exception as per overriding rules

 

AbstractExampleChild.java

A concrete class extending abstract class and overriding abstract method should provide implementation detail

Note: We got 2 options, while extending abstract classes

  • Either implement all abstract methods from abstract class
  • Else make implementing class itself as abstract for partial implementation
package in.bench.resources.abstractclass.example;

// extending abstract class & overriding abstract method
public class AbstractExampleChild extends AbstractExample {

	// default no-arg constructor
	AbstractExampleChild(){
		// do some initialization logic here
	}

	// overriding abstract method from abstract class
	@Override
	void myAbstractMethod() {
		System.out.println("AbstractExampleChild: Overriding abstract method from abstract class\n");
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String args[]) {

		// creating an object using abstract class type for reference
		AbstractExample ae = new AbstractExampleChild();

		// invoking abstract method using abstract class type
		ae.myAbstractMethod();

		// invoking concrete method using abstract class type
		ae.myConcreteMethod();
	}
}

Output:

AbstractExampleChild: Overriding abstract method from abstract class

AbstractExample: This is my concrete method in abstract class

 

Above concrete class,

  • firstly extends abstract class and overrides abstract method
  • main() method – the entry point to JVM to begin execution
  • creates an object of child class or extending concrete class with reference of abstract class
  • invokes abstract methods using newly created object and then invokes concrete method
  • prints appropriate message in the console

 

Whether abstract methods are allowed inside concrete class?

Compiler throws error, if we have abstract method inside concrete class

Compile-time error: This method requires a body instead of a semicolon

2_Abstract_class_abstract_method_inside_concrete_class

 

Relationship between Abstract class and abstract method:

  • A class without abstract methods still can be an abstract class, by adding abstract keyword to class declaration but vice-versa is not true
  • If there are any abstract methods, then class must be declared as abstract class with abstract keyword

 

What is the need of having an abstract class in Java, when object type of abstract class cannot be instantiated?

–> True, an abstract class cannot be instantiated; still having instance data members and constructor

–> This is to instruct compiler that no one should create an object of type abstract class

–> The reason is, every object has got some default behavior and specific behavior. In this case, abstract class is apt

–> So, we can put more common & general behavior with concrete method implementation and later extending (sub-classing) class can provide specific implementation for abstract methods in their own way

 

Whether main() method – the entry point to JVM to begin execution is allowed inside abstract class?

–> Yes, main() method is allowed inside abstract class but abstract class cannot be instantiated but we can access static fields and invoke static methods from main() method

 

AbstractExample.java

package in.bench.resources.abstractclass.example;

// abstract class
public abstract class AbstractExample {

	String demoString;
	static int demoCounter = 1;

	// default no-arg constructor
	AbstractExample(){
		// do some initialization logic here
	}

	static void staticMethod() {
		System.out.println("AbstractExample: static methods are allowed inside abstract class");
	}

	// abstract method declaration in abstract class
	abstract void myAbstractMethod();

	// concrete method definition in abstract class
	void myConcreteMethod() {
		System.out.println("AbstractExample: This is my concrete method in abstract class");
	}

	// main() method - the entry point to JVM to begin execution
	public static void main(String args[]) {

		System.out.println("Accessing static field demoCounter : " + AbstractExample.demoCounter);
		staticMethod();
	}
}

Output:

Accessing static field demoCounter : 1
AbstractExample: static methods are allowed inside abstract class

 

Explanation:

  • Above abstract class contains 3 types of methods viz.; abstract method, concrete method and static method
  • In addition to this, there is main() method which is an entry point to JVM to begin execution
  • In main() method, we are accessing static field using abstract class name and directly invoking static method
  • Prints appropriate messages in console

 

Points to remember about Abstract classes & methods:

Abstract Class:

  • An abstract class is declared with abstract keyword in class declaration
  • Extending or sub-classing abstract class must provide implementation details to all abstract methods
  • Else make extending class as abstract which means next implementing class must provide concrete implementation for all abstract methods
  • An abstract class can contain mix of both i.e.; abstract methods & concrete methods
  • It can have both default & parametrized constructor, but still it cannot be instantiated
  • An abstract class with no abstract method is denote that this class cannot instantiated, rather we can create object of type of extending class (sub class)
  • An abstract method is not allowed inside concrete class and compiler throws error stating “requires method body instead of a semicolon(;)
  • Both static and non-static fields can be declared inside abstract class
  • Abstract class can extend only one class, it could be either an abstract class or concrete class
  • An abstract can have main() method – the entry point to JVM to begin execution

Abstract Method:

  • An abstract method has no body
  • Method signature ends with semicolon(;)
  • Abstract method can throw exception
  • Abstract methods can be declared inside abstract class only
  • Abstract methods cannot be final or private or static
  • Only protected, default and public access modifiers allowed

 

References

https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

 

Read Also:

Happy Coding !!
Happy Learning !!