Abstract Class and Method in Java Programming
OOPs in Java
In this lesson, we will understand what is Abstract Class and Abstract Method in Java and how to implement them in programming along with some examples.
What is Abstract Class in Java?
An abstract class is a class whose object can't be created but can be used as a base class for other classes.
Example
abstract class Message
{
public void show()
{
System.out.println("I am method inside an abstract class");
}
}
class Data extends Message
{
public void display()
{
// Calling the show() method of the Message class
show();
}
}
public class Example
{
public static void main(String args[])
{
Data x=new Data();
x.show();
}
}
Output
I am method inside an abstract class
In the above example, the class Message is declared abstract, meaning that we can't create its object but can extend it into another class. Any attempt to create the object of the Message class will result in a compile-time error. See the example given below.
Example
abstract class Message
{
public void show()
{
System.out.println("I am method inside an abstract class");
}
}
public class Example
{
public static void main(String args[])
{
// This will give a compile-time error:
// Message is abstract; cannot be instantiated
Message x=new Message();
}
}
What is Abstract Method in Java?
An abstract method is a method that has no body. It is declared with the keyword abstract and must be overridden in a subclass.
Note: If a class contains an abstract method, then the class will also have to be declared abstract.
Example
abstract class Message
{
public void show()
{
System.out.println("I am method inside an abstract class");
}
// An abstract method without any body
public abstract void information();
}
class Data extends Message
{
// Overriding the abstract method infomation of the Message class
public void information()
{
System.out.println("Hello");
}
}
public class Example
{
public static void main(String args[])
{
Data x=new Data();
x.information();
x.show();
}
}
Output
Hello I am method inside an abstract class
In the above example, we declared a non-abstract method show() and an abstract method information() in the class Message. The Message class contains an abstract method, so it must also be declared abstract.
We have extended the class Data with the abstract class Message. The Message class contains abstract method information(), which we have overridden in the Data class.