IMT304 Lecture4
IMT304 Lecture4
A.S. Bunu
Recap of Previous lecture
Review of attributes, methods, constructors, and access
modifiers.
Discussion on the assignment and common issues
encountered.
1-2
Introduction to Inheritance
Definition: inheritance refers to a process by which one class
inherits properties (attributes and methods) from another. A key
feature of inheritance in this context is the extends keyword
Advantages of using Inheritance
Code Reusability: Avoid redundant code by inheriting
functionalities from the parent class.
Enhanced Readability: Hierarchical structures give a clearer,
more intuitive view of related classes.
Improved Maintainability: Change the parent class, and the
child classes get updated accordingly
1-3
When a class inherits from another, two main roles are defined:
Superclass (or Parent Class or Base class): This
class acts as the source for inheritance. Its blueprint
forms the basis from which subsequent classes
inherit attributes or methods from.
Subclass (or Child class or Derived class): This
is the class that does the inheriting. It will naturally
incorporate all non-private properties and methods
from its superclass and can also have additional
properties and methods of its own.
1-4
Syntax (Java):
1-5
Method Overloading vs. Method Overriding
Method overloading lets a class have several methods with
the same name but different parameters, allowing varied
actions based on parameters.
In contrast, method overriding enables a subclass to offer a
distinct behavior for an inherited method.
1-8
a) Compile-time Polymorphism (Static
Polymorphism):
This type of polymorphism is achieved when we overload a
method.
void print(int a) { ... }
void print(double b) { ... }
Here, the method's name remains the same, but the parameter lists vary – this
distinction in parameters is known as method signatures.
1-9
Benefits of Polymorphism
•Reusability: With Polymorphism, code components can
be leveraged across multiple classes, curtailing
redundancy.
•Extensibility: As business needs evolve, Polymorphism
ensures minimal disruptions when expanding
functionalities.
•Flexibility: Modules remain distinct, making systems
more manageable.
•Simplified Design: Systems designed with
Polymorphism are inherently organized and intuitive.
•Interchangeability: With Polymorphism, varying
implementations can be switched seamlessly.
•Enhanced Maintainability: With standardized
structures, tasks like debugging and updates become less
cumbersome.
1 - 10
Class Work
Create a Base Class and Derived Classes:
Write a class Vehicle with attributes make and model, and a
method displayInfo().
Create a derived class Car that extends Vehicle and adds an
attribute numDoors, and overrides displayInfo().
1 - 11
public class Vehicle {
String make;
String model;
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Number of doors: " + numDoors);
}
1 - 13