Meta Description: Learn how to create an abstract class with
a constructor and abstract and non-abstract methods in Java. See an example of
a subclass that inherits the abstract class and implements the abstract method.
The implementation of the code:
Source code:
abstract class AbstractClass {
public AbstractClass()
{
System.out.println("This is constructor of abstract class");
}
public abstract
void a_method();
public void
normal_method() {
System.out.println("This is a normal method of abstract
class");
}
}
class SubClass extends AbstractClass {
public void
a_method() {
System.out.println("This is abstract method");
}
}
public class Main {
public static void
main(String[] args) {
SubClass obj =
new SubClass();
obj.a_method();
obj.normal_method();
}
}
In this code, we have defined an abstract class
AbstractClass with a constructor that prints "This is constructor of
abstract class", an abstract method a_method, and a non-abstract method
normal_method that prints "This is a normal method of abstract
class".
We have also defined a concrete class SubClass that extends
the AbstractClass and provides the implementation for the abstract method
a_method.
Finally, we create an object obj of the SubClass class and
call the a_method and normal_method methods of the AbstractClass using the obj
reference. When we run the program,
we get the following output:
This is constructor of abstract class
This is abstract method
This is a normal method of abstract class
As we can see from the output, the constructor of the AbstractClass is called when we create an object of the SubClass because it is the superclass of SubClass. After that, we call the a_method method of the SubClass, which overrides the a_method method of the AbstractClass and prints "This is abstract method" to the console.
Finally, we call the normal_method method of the
AbstractClass, which is inherited by the SubClass, and prints "This is a
normal method of abstract class" to the console.
No comments:
Post a Comment