Java Abstraction

Abstraction in OOP is where creating interface or abstract classes to define the common behavior and reuse or implement it by extending it. In Java, Abstraction works with a keyword called Abstract.


Abstract Class:

A class declared with a keyword ‘abstract’ is said to be Abstract class. This abstract classes cannot be instantiated. It can be extended. Instantiation of abstract class will throw error.

An abstract class can have abstract methods as well as non abstract methods. Non abstract classes cannot hold abstract methods.

The abstract method should be declared without the braces like in the sample class below. speakChinese is the abstract method with a semicolon at the end.

Sample Class:


public abstract class ChineseType {
	
	abstract void speakChinese(String name);
	
	public void cookChineseReceipes(){
		System.out.println("I am cooking chinese receipes.");
	}
}

Now we shall see a sample example on how to use and extend an abstract class. We will take the above ChineseType abstract class for this example. We will be using the below Robot.java class to describe the behavior.

Implementing the Abstract method:

Sample Program:


public class Robot extends ChineseType {

	public static void main(String[] args) {
		
		// Will get compilation error - cannot instantiate the type chinesetype
		//ChineseType obj = new ChineseType();
		Robot machine = new Robot();
		machine.speakChinese("Mark 3");
		machine.cookChineseReceipes();		
	}

	@Override
	void speakChinese(String name) {
		System.out.println("I am " + name + " robot. I speak Chinese.");		
	}
}

In the above program, the abstract method ‘speakChinese’ is implemented compulsorily. The common ‘cookChineseReceipes’ method is directly accessed by its subclass.

Output:

I am Mark 3 robot. I speak Chinese.
I am cooking chinese receipes.

Posted on July 1, 2014 in Java for Beginners

Share the Story

Leave a reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Top