on Leave a Comment

Abstract Class and Methods in Java

In java, abstract class is declared with abstract keyword. An abstract class can contain both concrete (normal) method and abstract method. Abstract class is a way to achieve abstraction; however it does not provide 100% abstraction. 

Abstraction: It refers to hiding the background details and explanation of data and represents only essential information or functionality to the user.

Syntax of Abstract Class

abstract class class_name { }

Abstract Method

A method which is declared with abstract keyword and declared without any body is called abstract method. A class containing any abstract method then the class is declared as abstract class. Abstract method must be defined by its subclass; otherwise we must declare subclass as abstract class. If we do not defining abstract method in its subclass and do not declaring subclass as abstract, then we will get compile time error. Abstract method can never be final and static. 

Syntax of Abstract Method

abstract return_type function_name(); //no implementation

Example of Abstract Class with Non-Abstract Method

abstract class Example
{
	void show()
	{
		System.out.println("Abstract class with non-abstract method");
	}
}
class AbstractClass extends Example
{
	public static void main(String[] args) {
		AbstractClass obj = new AbstractClass();
		obj.show();
	}
}

Output:

Abstract class with non-abstract method

Example of Abstract Class with Abstract Method

abstract class Example
{
	abstract void show();
}
class AbstractClass extends Example
{
	void show()
	{
		System.out.println("Abstract class with abstract method");
	}
	public static void main(String[] args) {
		AbstractClass obj = new AbstractClass();
		obj.show();
	}
}

Output:

Abstract class with abstract method

Example of Abstract Class with Constructor

We can create object of an abstract class, so we can also define constructor in abstract class.

abstract class Example
{
	Example()
	{
		System.out.println("Abstract class Constructor");
	}
}
class AbstractClass extends Example
{
	public static void main(String[] args) {
		Example obj = new AbstractClass();		
	}
}

Output:

Abstract class Constructor

Usage of Abstract Class and Abstract Method

We know that a class containing any abstract method then the class is declared as abstract class. And an abstract method must be defined in its subclass. So, if we want overriding compulsory, then we can use abstract methods. 

Some Points about Abstract Class

We cannot instantiate abstract class directly.

Abstract class can contain both abstract method and non-abstract method.

Abstract class can have constructors and data members.

We cannot declare abstract constructor and abstract static method.

Abstract method must be defined in its subclass.

Abstract method can never be static and final.





0 comments:

Post a Comment