Why to use Abstract keyword in java language?

Abstract keyword is used to create an abstract class and abstract methods in java programs.

Abstract class: Abstract class in java is used as a base class in inheritance relationship. Abstract class have both non-abstract (implemented methods) and abstract (un-implemented methods) that must be overridden by sub classes.
Note that If we want to have common methods at one place and want to defer implementation of some of the methods to sub classes (derived classes) then we need to use abstract class as a base class.

Abstract method: Abstract keyword is used before un implemented method in abstract class that will be implemented by sub classes. Sub classes have to implement the abstract methods.

In below  java class example, we can see the use of Abstract class and abstract method.

In below abstract class Beverages, milk, hotWater, addSuger, addBasicElements methods are implemented whereas ingredient method is abstract and unimplemented. The class who extends the Beverages class must implement abstract method ingredient().

abstract class Beverages{	
	
	private void milk() {
		System.out.println("Hot Milk");
	}
	
	private void hotWater() {
		System.out.println("Hot water");
	}
	private void addSugar() {
		System.out.println("Hot Suger");		
	}
	
	public void addBasicElements() {		
		milk();
		hotWater();
		addSugar();		
	}
	
	abstract void ingredient();
		
}

NOTE: All methods in interfaces in java are by default public and abstract that are implemented by the class who implements the interfaces.

Related Posts