Abstract Class Example Java Program

Definition

An abstract type is a type of a nominative type system which cannot be instantiated directly. Abstract types are also known as existential types. An abstract type may provide no implementation or an incomplete implementation. The object-oriented form of abstract types is known as abstract base classes or simply abstract classes. A class extending an abstract class must implement all the abstract methods in the abstract class.

Syntax

abstract class class_name {
	//abstract method_name
}

Abstract Class Example Program

abstract class Employee { 
	String employeeId;
	String employeeName;
	
	Employee(String employeeId,String employeeName){
		this.employeeId = employeeId;
		this.employeeName = employeeName;
	}
	
	void displayName(String employeeName){
		System.out.println("Displaying name from non-abstract method : "+employeeName);
	}

	abstract void role(String employeeId,String employeeName); 
}

class AbstractClassDemo extends Employee{
	String employeeId;
	
	AbstractClassDemo(String employeeId,String employeeName){
		super(employeeId,employeeName);
		this.employeeId = employeeId;
	}
	
	//Overridden abstract method of Employee Class - role
	@Override
	public void role(String employeeId,String employeeName) {
		if(employeeId.equals("ID007")){
			System.out.println(employeeName+" : Captain and Wicket Keeper");
		}else if(employeeId.equals("ID099")){
			System.out.println(employeeName+" : Opening Batsman and Spin Bowler");
		}else{
			System.out.println("Not an Employee");
		}
	}
	
	public static void main(String args[]) { 
	Employee employeeObj = new AbstractClassDemo("ID007","M S Dhoni"); 
	AbstractClassDemo demoObj = new AbstractClassDemo("ID099","Sachin Tendulkar");

	//Implementing non-abstract method (This is not mandatory)
	employeeObj.displayName("M S Dhoni");

	//Implemeting abstract method in class Employee
	employeeObj.role("ID007","M S Dhoni"); 
	demoObj.role("ID099","Sachin Tendulkar"); 
	} 
}

Sample Output

Displaying name from non-abstract method : M S Dhoni
M S Dhoni : Captain and Wicket Keeper
Sachin Tendulkar : Opening Batsman and Spin Bowler