0% found this document useful (0 votes)
26 views4 pages

Method Overriding and Polymorphism

This document discusses method overriding and polymorphism in Java. It explains that a subclass can override a method from its parent class if the method signature is the same. This is known as runtime polymorphism. The document also discusses using the super keyword to call the parent method from the overridden method. It provides an example of overriding the show() method. The lab task asks students to create subclasses that override greeting methods to demonstrate polymorphism, and create subclasses of Car to calculate sale prices and demonstrate polymorphism.

Uploaded by

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

Method Overriding and Polymorphism

This document discusses method overriding and polymorphism in Java. It explains that a subclass can override a method from its parent class if the method signature is the same. This is known as runtime polymorphism. The document also discusses using the super keyword to call the parent method from the overridden method. It provides an example of overriding the show() method. The lab task asks students to create subclasses that override greeting methods to demonstrate polymorphism, and create subclasses of Car to calculate sale prices and demonstrate polymorphism.

Uploaded by

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

Method Overriding Lab # 9

LAB # 9

METHOD OVERRIDING & POLYMORPHISM

OBJECTIVE:
To study Method Overriding and polymorphism.

THEORY:

9.1 OVERRIDING A BASE CLASS METHOD


You can define a method in a derived class that has the same signature as a
method in the base class. The access attribute for the method in the derived
class can be the same as that in the base class or less restrictive, but it
cannot be more restrictive. As shown in the figure.

This means that if you declare a method as public in the base class, for
example, any derived class definition of the method must also be declared as
public. You cannot omit the access attribute in the derived class in this case,
or specify it as private or protected. When you define a new version of a base
class method in this way, the derived class method will be called for a derived
class object, not the method inherited from the base class. The method in the
derived class overrides the method in the base class. The base class method
is still there though, and it is still possible to call it in a derived class. Let’s see
an overriding method in a derived class in action.

// Method overriding.

Object Oriented Programming - OOPs 1


Method Overriding Lab # 9

class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
[Link]("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}

Output:

When show( ) is invoked on an object of type B, the version of show( )


defined within B is used. That is, the version of show( ) inside B overrides the
version declared in A.

If you wish to access the superclass version of an overridden function, you


can do so by using super. For example, in this version of B, the superclass
version of show( ) is invoked within the subclass’ version. This allows all
instance variables to be displayed.

class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}

Object Oriented Programming - OOPs 2


Method Overriding Lab # 9

void show() {
[Link](); // this calls A's show()
[Link]("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the
following output:

Output

9.2 POLYMORPHISM

Class inheritance is not just about reusing classes that you have already
defined as a basis for defining a new class. It also adds enormous flexibility to
the way in which you can program your applications, with a mechanism called
polymorphism. So what is polymorphism? The word polymorphism generally
means the ability to assume several different forms or shapes. In
programming terms it means the ability of a single variable of a given type to
be used to reference objects of different types and to automatically call the
method that is specific to the type of object the variable references. This
enables a single method call to behave differently, depending on the type of
the object to which the call applies. This is illustrated in Figure.

Polymorphism describes a language’s ability to process objects of various


types and classes through a single, uniform interface.

Object Oriented Programming - OOPs 3


Method Overriding Lab # 9

Polymorphism in Java has two types: Compile time polymorphism (static


binding) and Runtime polymorphism (dynamic binding). Method overloading is
an example of static polymorphism, while method overriding is an example of
dynamic polymorphism.
Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference
is used to refer to a child class object.

LAB TASK

1. Create a class Card, and its children classes are Valentine, Holiday,
and Birthday. A card class will have a greeting () method that writes out
a greeting. Each type of card contains an appropriate greeting. The
Holiday card says "Season's Greetings." The Birthday card says
"Happy Birthday." The Eid card says "Happy blissful Eid". Create
objects of the three child classes: Holiday, Birthday and Eid and show
the polymorphic behavior (call the greeting methods from each object).

2. Create a super class called Car. The Car class has the following fields
and methods. int speed; double regularPrice; String color; double
getSalePrice(); Create a sub class of Car class and name it as Truck.
The Truck class has the following fields and [Link] weight;
doublegetSalePrice();//Ifweight>2000,10%[Link],20%disc
ount. Create a subclass of Car class and name it as Ford. The Ford
class has the following fields and methods. int year; int
manufacturerDiscount; double getSalePrice();//From the sale price
computed from Car class, subtract the manufacturer Discount. Create
MyOwnAutoShop class which contains the main() method. Perform the
following within the main() method. Create two instances of the Ford
and Truck class and initialize all the fields with appropriate values. Use
super(...) method in the constructor for initializing the fields of the super
class. Create an instance of Car class and initialize all the fields with
appropriate values. Display the sale prices of all instance. Show
polymorphic behavior.

ASSIGNMENT
1. Is constructor overloading polymorphism? If Yes or No, Justify your
Answer.
2. Figure out the type of polymorphism is method overloading and method
overriding respectively.

Object Oriented Programming - OOPs 4

Common questions

Powered by AI

Method overriding is a key aspect of polymorphism in object-oriented programming. Polymorphism allows a single function call to execute different implementations based on the object's type that calls the method. Specifically, method overriding occurs when a derived class implements a method with the same signature as a method in its base class, thereby enabling runtime polymorphism. This allows the method of an object to dynamically resolve to the derived class's implementation at runtime .

Method overriding and method overloading exemplify two types of polymorphism in Java. Method overriding is an example of runtime polymorphism wherein a derived class provides a specific implementation of a method that already exists in its parent class, allowing method calls to dynamically resolve to subclass implementations at runtime. On the other hand, method overloading is an example of compile-time polymorphism, where multiple methods share the same name but have different parameter lists, allowing the appropriate method to be statically bound at compile time. Both mechanisms enable flexibility and extendability by enabling methods to be used on object types that are not determined until execution .

In method overriding, access modifiers play a critical role in maintaining the visibility and accessibility of methods. The overridden method in the derived class cannot have a more restrictive access level than the method it overrides. For example, if a method in the base class is declared as public, the overriding method in the derived class must also be public. This requirement ensures that the derived class method can be invoked in all the places where the base class method could be invoked, maintaining polymorphic behavior by preserving interface consistency .

Compile-time polymorphism, or static binding, occurs when the method being called is determined at compile time. An example of this is method overloading, where multiple methods have the same name but different parameters. Runtime polymorphism, or dynamic binding, occurs when the method to be invoked is determined at runtime, which is primarily achieved through method overriding. Here, a base class reference is used to call a method, but the method that gets executed is the overridden version in the derived class .

Method overriding facilitates polymorphic behavior by allowing a derived class to provide a specific implementation of a method that is already defined in its base class. When a method call is made on a base class reference that points to a derived class object, the overridden method in the derived class is executed. This behavior allows the program to determine the appropriate method at runtime, based on the actual object type, thereby enabling runtime polymorphism .

Constructor overloading is not considered polymorphism because it involves static binding and does not provide different implementations that can be called dynamically at runtime. Polymorphism involves a single method signature existing across different class hierarchies, allowing different behaviors to be invoked depending on the object type. In contrast, constructor overloading occurs at compile time and simply allows the instantiation of objects with different initial parameters. It does not provide the runtime method resolution seen in polymorphism .

Polymorphism enhances flexibility and reuse in programming by allowing objects to be treated as instances of their parent class rather than their actual class, thus enabling code that works on the parent class to also work with any subclass objects. This supports dynamic method resolution, which means that the appropriate method specific to an object's actual class is executed, even though the call was made on a parent class type reference. This greatly simplifies code maintenance and reuse because methods can be written to work with the parent class, and they will work correctly with any subclass that overrides those methods. As such, polymorphism supports a uniform interface for different objects or classes .

Class inheritance contributes to polymorphic behavior by allowing a base class to define a set of methods that can be overridden by derived classes. This hierarchy enables objects of derived classes to be treated as objects of the base class type, thus allowing the base class reference to point to derived class objects. Through this setup, method calls on the base class reference trigger the execution of overridden methods in derived classes, which embodies polymorphic behavior. This mechanism enables programs to process objects of different classes through a single interface, thus enhancing flexibility and reuse .

The "super" keyword is used in method overriding to explicitly call a method from the superclass within the overridden method in the derived class. For instance, if a method "show" is overridden in a derived class but the behavior of the superclass 'show' method is needed, "super.show()" can be invoked within the derived class method. This allows both the superclass's method functionality and the extended functionality of the derived class to execute, therefore retaining and extending the original behavior .

Creating objects from child classes in a class hierarchy demonstrates polymorphic behavior as method calls made on these objects execute the overridden methods in the child classes rather than the methods defined in the parent class. When a parent class reference variable is used to refer to a child class object, and a method is invoked, the method defined in the child class is executed, illustrating runtime polymorphism. This behavior is because the exact method resolved is based on the actual object type, not the reference type, during runtime .

You might also like