0% found this document useful (0 votes)
9 views5 pages

Java Polymorphism Examples and Lab

The document contains Java code examples demonstrating polymorphism, method overloading, and method overriding. It includes a base class 'Person' with a derived class 'Father', a 'Helper' class with overloaded 'Multiply' methods, and multiple subclasses of 'Parent' showcasing overridden 'Print' methods. Additionally, it features an 'Animal' class with subclasses 'Pig' and 'Dog' that override the 'animalSound' method.

Uploaded by

mercy joyce
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Java Polymorphism Examples and Lab

The document contains Java code examples demonstrating polymorphism, method overloading, and method overriding. It includes a base class 'Person' with a derived class 'Father', a 'Helper' class with overloaded 'Multiply' methods, and multiple subclasses of 'Parent' showcasing overridden 'Print' methods. Additionally, it features an 'Animal' class with subclasses 'Pig' and 'Dog' that override the 'animalSound' method.

Uploaded by

mercy joyce
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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]();

Common questions

Powered by AI

Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This enhances polymorphism as it enables the use of a superclass type reference to dynamically invoke the overridden methods of various subclasses at runtime. For example, in the 'Person' and 'Father' classes, the method 'role()' is overridden in the 'Father' class, and when called on a 'Person' reference holding a 'Father' object, it executes the 'Father's implementation. Similarly, in the 'Animal', 'Pig', and 'Dog' classes, the 'animalSound()' method is overridden in each subclass to provide specific sounds. This same method name invokes different implementations based on the subclass instance .

Method signatures, which consist of the method name and its parameter list, are essential in distinguishing between method overloading and method overriding. In method overloading, different methods within the same class share the same name but have different parameter lists, as seen in the 'Helper' class where 'Multiply' methods differ by argument types (integers and doubles). In method overriding, the child class provides a specific implementation for a method already defined in its parent class with the same signature, as seen in the 'Animal' class hierarchy where 'animalSound()' methods in 'Pig' and 'Dog' have the same signature as in the 'Animal' class but provide different functionalities .

The 'Geeks' class illustrates dynamic method dispatch through the use of a superclass reference ('Parent') pointing to subclass objects ('subclass1' and 'subclass2'). When 'Print()' is called on these references, it dynamically binds to the appropriate method version at runtime, executing 'subclass1's and 'subclass2's respective 'Print()' implementations, showing the different outputs—'subclass1' and 'subclass2'. This demonstrates dynamic method dispatch, a fundamental aspect of runtime polymorphism, where method resolution is delayed until runtime .

Method overriding impacts software design patterns by promoting polymorphic behavior, which is fundamental to many patterns such as the Strategy and Observer patterns. In the examples, method overriding in classes like 'Father', 'subclass1', and 'subclass2', alongside 'Pig' and 'Dog', enables flexibility in substituting algorithms and responses, supporting design patterns that require interchangeable behaviors. This capability facilitates encapsulating algorithms and varying parts of the system without modifying client code, aligning with the open/closed principle and enhancing design scalability and adaptability .

In the 'Main' class, polymorphism is demonstrated by declaring a reference of type 'Person', which is the superclass, and assigning it an object of type 'Father', the subclass. When the 'role()' method is called on this reference, the overridden method in the 'Father' class is executed, displaying 'I am a father.' This behavior illustrates polymorphism, where the call to the method 'role()' on a superclass reference holding a subclass object results in the execution of the subclass's method implementation .

Method overriding in 'Pig' and 'Dog' enhances system flexibility and extensibility by allowing new classes to define specific behaviors while adhering to a general contract. Each subclass provides its unique implementation for 'animalSound()' without altering the original 'Animal' class, facilitating future extensions like adding more subclasses with distinct sounds. This design leverages polymorphism, enabling code reuse and robust modification with minimal impact on existing functionalities, thus accommodating growth and changes efficiently .

Specifying parameter types in method overloading is crucial as it determines which version of the method is called during a function call. In the 'Helper' class, the 'Multiply' method is overloaded to accept both integer and double parameters. The choice of method executed depends on the argument types supplied during the call (e.g., passing integers calls the integer version, and passing doubles calls the double version). This specificity allows for more flexible and intuitive code usage, leveraging Java's compile-time type checking to determine method execution paths .

In the provided examples, inheritance allows subclasses to reuse code from superclasses, promoting maintainability by centralizing common behaviors. For instance, the 'Father' class inherits from 'Person', and both 'subclass1' and 'subclass2' inherit from 'Parent', each inheriting core functionalities (e.g., method headers) and only implementing specific differences. This reuse reduces redundancy and ensures consistency, while any superclass changes automatically propagate to subclasses, simplifying maintenance without modifying each subclass individually .

Method overloading occurs when multiple methods have the same name but different parameter lists within the same class. It is demonstrated in the 'Helper' class where 'Multiply' methods accept different types of parameters (integer and double) but retain the same method name. On the other hand, method overriding involves redefining a method in a subclass that already exists in its superclass. The overriden methods have the same signatures as in the superclass, but different implementations. This is demonstrated in subclasses 'subclass1' and 'subclass2' where they both override the 'Print' method from the 'Parent' class, providing their unique behaviors .

The 'Animal' class hierarchy exemplifies object-oriented principles, particularly inheritance and polymorphism, through method overriding. The 'Animal' class defines the method 'animalSound()' with a general implementation. Its subclasses, 'Pig' and 'Dog', override this method to provide specific behaviors ('wee wee' and 'bow wow', respectively). This use of method overriding allows each subclass to customize inherited behaviors while maintaining the same method signature, supporting polymorphism where the reference type determines the method execution at runtime .

You might also like