Polymorphism Lab Programs
// Base class Person
class Person {
// Method that displays the
// role of a person
void role() {
[Link]("I am a person.");
}
}
// Derived class Father that
// overrides the role method
class Father extends Person {
// Overridden method to show
// the role of a father
@Override
void role() {
[Link]("I am a father.");
}
}
public class Main {
public static void main(String[] args) {
// Creating a reference of type Person
// but initializing it with Father class object
Person p = new Father();
// Calling the role method. It calls the
// overridden version in Father class
[Link]();
}
}
Method Overloading Example-1
// Method overloading By using
// Different Types of Arguments
// Class 1
// Helper class
class Helper {
// Method with 2 integer parameters
static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class Geeks
{
// Main driver method
public static void main(String[] args) {
// Calling method by passing
// input as in arguments
[Link]([Link](2, 4));
[Link]([Link](5.5, 6.3));
}
}
Method Overriding Example-1
// Java Program for Method Overriding
// Class 1
// Helper class
class Parent {
// Method of parent class
void Print() {
[Link]("parent class");
}
}
// Class 2
// Helper class
class subclass1 extends Parent {
// Method
void Print() {
[Link]("subclass1");
}
}
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print() {
[Link]("subclass2");
}
}
// Class 4
// Main class
class Geeks {
// Main driver method
public static void main(String[] args) {
// Creating object of class 1
Parent a;
// Now we will be calling print methods
// inside main() method
a = new subclass1();
[Link]();
a = new subclass2();
[Link]();
}
}
Method Overriding Example-2
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
class Pig extends Animal {
public void animalSound() {
[Link]("The pig says: wee wee");
class Dog extends Animal {
public void animalSound() {
[Link]("The dog says: bow wow");
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
[Link]();
[Link]();
[Link]();