Polymorphism is a fundamental concept in Java that refers to the ability of objects to take on multiple forms.
class Primary {
public void sameName() {
System.out.println("I am from Primary Class");
}
}
class SecondaryA extends Primary {
public void sameName() {
System.out.println("I am from SecondaryA Class");
}
}
class SecondaryB extends Primary {
public void sameName() {
System.out.println("I am from SecondaryB Class");
}
}
public class Main {
public static void main(String[] args) {
Primary primObj = new Primary();
Primary secAObj = new SecondaryA();
Primary secBObj = new SecondaryB();
primObj.sameName();
secAObj.sameName();
secBObj.sameName();
}
}
Here's an explanation of the code block by block:
class Primary {
public void sameName() {
System.out.println("I am from Primary Class");
}
}
This code defines a class Primary
with a method sameName()
, which simply prints "I am from Primary Class" to the console.
class SecondaryA extends Primary {
public void sameName() {
System.out.println("I am from SecondaryA Class");
}
}
This code defines a subclass SecondaryA
of the Primary
class. SecondaryA
also has a sameName()
method, but in this case, it prints "I am from SecondaryA Class" to the console. Since SecondaryA
extends Primary
, it inherits the sameName()
method from Primary
but overrides it with its own implementation.
class SecondaryB extends Primary {
public void sameName() {
System.out.println("I am from SecondaryB Class");
}
}
This code defines another subclass SecondaryB
of the Primary
class. SecondaryB
also has a sameName()
method, which prints "I am from SecondaryB Class" to the console. Again, since SecondaryB
extends Primary
, it inherits the sameName()
method from Primary
but overrides it with its own implementation.
public class Main {
public static void main(String[] args) {
Primary primObj = new Primary();
Primary secAObj = new SecondaryA();
Primary secBObj = new SecondaryB();
primObj.sameName();
secAObj.sameName();
secBObj.sameName();
}
}
This code defines the Main
class with a main()
method. In the main()
method, we create objects of Primary
, SecondaryA
, and SecondaryB
classes and assign them to variables of type Primary
. We then call the sameName()
method on each of these objects. The output will be:
I am from Primary Class
I am from SecondaryA Class
I am from SecondaryB Class
This demonstrates the concept of polymorphism in Java, where the same method (sameName()
) can be called on different objects (primObj
, secAObj
, and secBObj
), and the implementation of the method that is called depends on the actual type of the object that the method is called on.
No comments:
Post a Comment