First, we create an abstract class called "Parent"
with an abstract method called "message". The "abstract"
keyword before the class and method means that they cannot be instantiated
directly, but must be subclassed and implemented. In this case, any subclass of
"Parent" must implement the "message" method.
abstract class Parent {
public abstract
void message();
}
Next, we create two subclasses of "Parent" called
"FirstSubclass" and "SecondSubclass". Both of these classes
extend the "Parent" class and implement the "message"
method. The implementation of the "message" method is different for
each subclass - the first prints "This is first subclass", and the
second prints "This is second subclass".
class FirstSubclass extends Parent {
public void
message() {
System.out.println("This is first subclass");
}
}
class SecondSubclass extends Parent {
public void
message() {
System.out.println("This is second subclass");
}
}
Finally, we create a "Main" class with a
"main" method. In this method, we create objects of both subclasses
using the "Parent" class as the reference type. This allows us to
call the "message" method of both subclasses using the same reference
type. We then call the "message" method on each object, which prints
the message specific to each subclass.
public class Main {
public static void
main(String[] args) {
Parent obj1 =
new FirstSubclass();
Parent obj2 =
new SecondSubclass();
obj1.message();
obj2.message();
}
}
When we run the "Main" class, the output will be:
This is first subclass
This is second subclass
This demonstrates the concept of polymorphism in
object-oriented programming, where different objects can have different behaviors
even though they are accessed through the same reference type.
No comments:
Post a Comment