Abstract Keyword

Abstract keyword is used with class and method declaration. Abstract defines incomplete data structures where the final or complete implementation will be done by its child class. In Java, Abstract used for defining the common behaviour for a class and let the child class to override the common behaviour. Some of the characteristics of the abstract keyword are :

Characteristics of Abstract

  • Abstract class may or may not have abstract methods
  • Abstract classes can not be instantiated
  • If a class declares abstract method, the class must be declared as abstract class
  • If a class extedns abstract class and it is not implementing the inherited abstract methods, then child class also has to be defined as abstract
  • An abstract method is a method that is declared without an implementation
  • An abstract class may have static fields and static methods. You can use these static members with a class reference (for example, bstractClass.staticMethod()) as you would with any other class.

Abstract Keyword Example

Employee.java

package javabeat.net.core;

public abstract class Employee {
	public void getEmpId(){
		System.out.println("EMPLOYEE ID");
	}
	public abstract void getRole();
}

Manager.java

package javabeat.net.core;

public class Manager extends Employee {
	@Override
	public void getRole() {
		System.out.println("Manager Role");
	}
}

Clerk.java

package javabeat.net.core;

public class Clerk extends Employee{
	@Override
	public void getRole() {
		System.out.println("Clerk Role");
	}
}

AbstractDemo.java

package javabeat.net.core;

public class AbstractDemo {
	public static void main(String args[]){
		Employee manager = new Manager();
		Employee clerk = new Manager();
		manager.getEmpId();
		manager.getRole();
		clerk.getEmpId();
		clerk.getRole();
	}
}

Output

EMPLOYEE ID
Manager Role
EMPLOYEE ID
Manager Role

If you look at the above example code, You will understand the use of abstract keyword in Java. If you have any questions, please write it in the comments section.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*