In this article we will see what are 'Abstract classes in Java', and how to use them with example.

Abstract classes in Java

In Java abstract classes are the classes which can contain both Concrete and Abstract methods.
abstract class Impl{
	// abstract method
	public abstract void getName();
	
	// concrete method
	public void getColor(){
		
	}
}
If any class extends an abstract class than the subclass must override all the abstract methods of the abstract superclass.
package com.tb.demo;

abstract class Impl {
	// abstract method
	public abstract void getName();

	// concrete method
	public void getColor() {

	}
}

public class Main extends Impl {
	@Override
	public void getName() {
		// TODO Auto-generated method stub

	}

}

Abstract methods in Java

Abstract methods are the methods which are declared without any body, these methods can not be declared as static or final.

Any abstract method has to be implemented by sub class of their container (class or interface).

Abstract methods in abstract class

abstract class Impl {
	// abstract method
	public abstract void getName();
}

public class Main extends Impl {
	@Override
	public void getName() {
		// TODO Auto-generated method stub

	}

}

Abstract methods in interface

interface Impl {
	// abstract method
	public abstract void getName();
}

public class Main implements Impl {
	@Override
	public void getName() {
		// TODO Auto-generated method stub

	}

}
Abstract classes can have Constructors, but can not be instantiated. Any class having even a single abstract method must be declared abstract.

When to use abstract Classes ?

Abstract classes are used when two or more sub classes tends to use some methods as same but for some methods they expects their own and different implementation.

In this article we have seen what are 'Abstract classes in Java', and how to use them with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java