Practical-26
Write a Java Program to implement abstract class and abstract method.
Introduction
An abstract class is a special type of class in Java which contains abstract methods and these methods lack implementation, meaning they have no body. Whereas in an abstract class, the methods have the declaration and a keyword “abstract” which prefixes the method declaration. An abstract class has to be extended and the methods defined in it have to be implemented in the child class. Any class that contains at least one abstract method must be declared abstract itself, it cannot implement its own abstract methods.
Code
public abstract class AbstractClass {
public abstract void abstractFunction1();
public abstract void abstractFunction2();
public void regularFunction(){
System.out.println("Regular Function can also declare in Abstract Class");
}
}
public class ChildClass extends AbstractClass {
@Override
public void abstractFunction1() {
System.out.println("method implementation of abstract method 1");
}
@Override
public void abstractFunction2() {
System.out.println("method implementation of abstract method 2");
}
public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.abstractFunction1();
obj.abstractFunction2();
obj.regularFunction();
}
}
Output
method implementation of abstract method 1
method implementation of abstract method 2
Regular Function can also declare in Abstract Class
In this program AbstractClass is an abstract class which contains two abstract functions and a regular function which prints a statement. The ChildClass extends the AbstractClass which means that it can be used to access the abstract methods of parent class and the same must be implemented in the child class. The @Override annotation is used to ensure that the correct function is being overridden in the child class. Lastly, inside the main() function the ChildClass object is created and object is used to access the abstract and regular methods of the parent class.