Given the following package contents, write a short program (class Insecttest) that demonstrates the concept of polymorphism using the classes provided in JAVA
package insect;
public class Insect {
public void nickname () {
System.out.println ("bug");
}
}
public class Flying extends Insect {
@Override
public void nickname() {
System.out.println ("flying bug");
}
}
public class Jumping extends Insect{
@Override
public void nickname() {
System.out.println ("jumping bug");
}
}
The answer to this question is as follows:
The polymorphism is of two types:
1.static polymorphism(Method overloading)
2.Dynamic polymorphism(Method overriding)
From the above question, Dynamic polymorphism is implemented
I am trying to execute all the classes at a time so I removed public for the classes if you want to execute you can save as files like insect.java , flying.java , jumping.java
The code is as follows:
class Insect
{//Declaring the class Insect it is the base class for the
remaining
public void nickname()
{
System.out.println("bug");
}
}
class Flying extends Insect
{ //decalring the class Flying that is inherited from the Insect
class
@Override //overriding the insect class method
public void nickname()
{
System.out.println("flying bug");
}
}
class Jumping extends Insect
{//decalring the class Jumping that is inherited from the Insect
class
@Override//overriding the insect class method
public void nickname()
{
System.out.println("jumping bug");
}
}
public class Test{
public static void main(String[] args){
//Overiding the method that is insect with the method in
Flying
Insect insect1=new Flying();
insect1.nickname();
//Overiding the method that is insect with the method in
jumping
Insect insect2=new Jumping();
insect2.nickname();
//calling the method in the insect class
Insect insect3=new Insect();
insect3.nickname(); // prints Vehicles can move!!
}
}
Get Answers For Free
Most questions answered within 1 hours.