Advance Programming unit-2
Advance Programming unit-2
Inheritance
Polymorphism using Inheritance in OOP
1. What is Polymorphism?
● Definition: Polymorphism allows one interface to be used for a general class of
actions.
● Example: A function can behave differently based on the object that calls it.
Polymorphism using Inheritance in OOP
2. Key Concept: Inheritance
● Inheritance: A mechanism where one class (child class) inherits properties and
behaviors from another (parent class).
● Enables reusability and extension of code.
Polymorphism using Inheritance in OOP
3. How Polymorphism Works with Inheritance
4. Code Example:
Polymorphism using Inheritance in OOP
Polymorphism using Inheritance in OOP
Explanation:
● Definition: The process by which Java determines which method to invoke when
multiple methods with the same name exist.
● Occurs in cases of:
○ Inheritance (overriding methods)
○ Polymorphism (method calls through reference types)
Method Resolution in Java
2. Method Resolution in Inheritance
● Method Overriding:
○ Child class overrides a method from the parent class.
○ During method call, Java determines the correct method to invoke based on the
runtime object type, not the reference type
Method Resolution in Java
3. How Method Resolution Works:
● Inheritance: Allows a class to inherit properties and methods from another class.
● Interface: Defines a contract that a class must follow by implementing abstract
methods.
Interface v/s Inheritance in Java
2. Key Differences
Access Modifiers Can inherit concrete methods Cannot have fields, only
and fields. method signatures.
1. Inheritance:
Interface v/s Inheritance in Java
2. Interface:
Interface v/s Inheritance in Java
4. When to Use:
● Inheritance:
○ When there is a clear “is-a” relationship.
○ For code reuse (common properties/methods).
● Interfaces:
○ When unrelated classes need to share common behavior.
○ To achieve multiple inheritance of behavior.
Interface v/s Inheritance in Java
5. Conclusion
● Inheritance: A mechanism where one class acquires the properties and behaviors
(methods) of another class.
● The class that is inherited is called the Parent (Base) class.
● The class that inherits is called the Child (Derived) class.
Example
Constructor Invocation in Inheritance Tree
Constructors in Inheritance
1. Parent Class Constructor is always called first, even if you create an object of the
child class.
2. Then, the Child Class Constructor is invoked.
Why?
○ The child class might depend on the parent class for initialization.
Constructor Invocation in Inheritance Tree
Constructor Flow in Single Inheritance
Constructor Invocation in Inheritance Tree
Output:
Constructor Invocation in Inheritance Tree
Default Constructor Invocation
● If no constructor is defined in the parent class, the compiler automatically calls the
default constructor of the parent class.
● If a constructor is defined, it must be explicitly invoked by the child class.
Constructor Invocation in Inheritance Tree
Invoking Parameterized Constructors
● A child class can invoke a parameterized constructor of the parent class using the
super keyword (in Java) or an initializer list (in C++).
Constructor Invocation in Inheritance Tree
Example with Parameterized Constructor (C++)
Constructor Invocation in Inheritance Tree
Output:
Constructor Invocation in Inheritance Tree
Constructor Invocation in Multilevel Inheritance
Can have both abstract and non-abstract All methods are abstract (in some
methods languages)
Key Points:
● All fields (instance variables) are set once, typically through the constructor.
● Any attempt to modify the object's state results in a new object being created.
Characteristics of Immutable Classes
Main Characteristics:
● Final Fields: The class variables are usually final (or equivalent, depending on the
language).
● No Setters: There are no mutator methods (like setters) to change the object's state
after it's initialized.
● Constructor Initialization: Object’s state is set at construction and never modified.
Why Use Immutable Classes?
Advantages of Immutability:
● String: The String class in Java is immutable. Once a string object is created, it cannot
be changed.
● Wrapper Classes: Classes like Integer, Double, etc., in Java are immutable.
● Mutable Fields: If your class contains mutable objects (like lists), ensure these are not
exposed directly.
● Deep Immutability: Use defensive copying if needed for mutable fields.
Consideration:
● The Object class is the root class of the Java class hierarchy.
● Every class in Java implicitly extends Object if no other superclass is specified.
Key Points:
● Common Ancestor: All classes are descendants of Object, ensuring that every Java
object shares a basic set of methods.
● Polymorphism: Methods that accept Object type can accept instances of any class.
Key Methods of the Object Class
Important Methods Inherited by All Classes:
1. toString():
○ Returns a string representation of the object.
○ Often overridden to provide meaningful output.
2. equals(Object obj):
○ Compares two objects for equality.
○ Typically overridden to provide custom equality logic.
3. hashCode():
○ Returns an integer hash code for the object.
○ Should be overridden when equals() is overridden.
4. clone():
○ Creates and returns a copy of the object (shallow copy by default).
toString() Method in Detail
Default Behavior:
● The default implementation checks if the two object references point to the same memory location.
● Objects that are equal according to equals() must have the same hash code.
Override Example:
@Override
}
clone() Method in Detail
Default Behavior:
● finalize():
○ Called by the garbage collector before an object is destroyed (deprecated in Java
9).
● wait() and notify():
○ Used for thread synchronization.
● getClass():
○ Returns the runtime class of the object.
Conclusion
Summary:
● The Object class provides essential methods for all Java objects.
● toString(), equals(), and hashCode() are commonly overridden for custom
behavior.
● Understanding and overriding these methods correctly is key to effective object-oriented
programming in Java.
Comparing Objects
(Equals method, Comparable, and Comparator Interfaces)
Why Compare Objects?
Definition:
● Object Comparison allows determining if objects are equal or which one is "greater."
Use Cases:
Custom Implementation:
Example: @Override
}
The hashCode() Method (Connection with equals())
Key Rule:
● Objects that are equal (equals() == true) must have the same hashCode().
Override Example:
@Override
}
The Comparable Interface
Purpose:
Method Signature:
Key Points:
● Returns a negative integer if the current object is less than the specified object.
● Returns 0 if they are equal.
● Returns a positive integer if the current object is greater than the specified object.
Implementing Comparable
● When a class implements Comparable, objects can be sorted using Collections.sort() or Arrays.sort().
The Comparator Interface
Purpose:
Method Signature:
public int compare(T obj1, T obj2)
Key Points:
● Can be used to define multiple comparison strategies (e.g., compare by name, by age,
etc.).
● Provides greater flexibility than Comparable.
Implementing Comparator
@Override
Usage in Collections:
Comparator:
Output: