Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Advance Programming unit-2

Uploaded by

mayank.7554s
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Advance Programming unit-2

Uploaded by

mayank.7554s
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Polymorphism using

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

● A base class defines a common interface.


● Derived classes implement or override methods.
● A parent class reference can point to child class objects.
Polymorphism using Inheritance in OOP

4. Code Example:
Polymorphism using Inheritance in OOP
Polymorphism using Inheritance in OOP
Explanation:

● Animal is the base class.


● Dog and Cat are derived classes that override the sound() method.
● The base class reference (Animal) can point to objects of derived classes (Dog, Cat).
● Polymorphism occurs when the method is called based on the object type, not the
reference type.
Polymorphism using Inheritance in OOP
5. Benefits of Polymorphism

● Flexibility: Use a common interface to handle different types.


● Scalability: Easily extend with new types without altering existing code.
Method Resolution
Method Resolution in Java
1. What is Method Resolution?

● 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:

1. Static Binding (Compile-time):


○ Decides method signature (name, parameters) during compilation.
○ Happens with method overloading.
2. Dynamic Binding (Runtime):
○ Decides which version of the method (parent or child) to call based on the actual
object type during runtime.
○ Involves method overriding.
Method Resolution in Java
4. Code Example:
Method Resolution in Java
5. Key Points:

● Compile-time binding: For method overloading (same name, different parameters).


● Runtime binding: For method overriding (same name and parameters, different
implementation).
● Object type determines which overridden method is invoked.
Interfaces v/s Inheritance
Interface v/s Inheritance in Java
1. Overview

● 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

Aspects Inheritance Interface

Purpose To inherit features (methods To specify behaviors (methods)


and fields). that must be implemented

Keyword extends implements

Multiple Inheritance Not allowed (a class can Allowed (a class can


extend only one class). implement multiple interfaces).

Access Modifiers Can inherit concrete methods Cannot have fields, only
and fields. method signatures.

Method Implementation Inherited methods can be Methods must be implemented


overridden. in the class.
Interface v/s Inheritance in Java
3. Use Case Examples

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

● Use inheritance for hierarchical relationships and code reuse.


● Use interfaces for defining contracts across different, unrelated classes.
Constructor Invocation in
Inheritance Tree
Constructor Invocation in Inheritance Tree
What is Inheritance?

● 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

● A constructor is a special function used to initialize objects.


● In an inheritance hierarchy, constructors of parent and child classes are involved when
an object of the child class is created.
Constructor Invocation in Inheritance Tree
Constructor Invocation Order

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

1. Grandparent Class Constructor


2. Parent Class Constructor
3. Child Class Constructor
Constructor Invocation in Inheritance Tree
Example of Multilevel Inheritance
Constructor Invocation in Inheritance Tree
Constructor Invocation in Inheritance Tree
Key Points to Remember

● Parent class constructors are called first in inheritance.


● Default constructors are called automatically if no constructor is defined.
● Use super() in Java and initializer lists in C++ to call parameterized parent
constructors.
● Order of constructor invocation follows the inheritance chain: top to bottom.
Constructor Invocation in Inheritance Tree
Summary

● Constructor invocation ensures proper initialization in inheritance.


● Always starts from the base class and moves down to the derived class.
● For parameterized constructors, explicit calls may be needed.
Abstract Classes
What is an Abstract Class?
● An abstract class is a class that cannot be instantiated directly.
● It serves as a blueprint for other classes.
● It often contains one or more abstract methods (methods without implementation).
● Derived classes must provide implementations for the abstract methods.
Characteristics of Abstract Classes
1. Cannot create objects of abstract classes.
2. Can have both abstract (unimplemented) and non-abstract (implemented) methods.
3. Forces derived classes to implement the abstract methods.
4. Can have constructors and member variables.
Syntax of an Abstract Class (C++/Java)
Why Use Abstract Classes?
● To provide a common interface for all subclasses.
● Enforces polymorphism by ensuring derived classes follow a contract.
● Used when you want to share code across multiple related classes while ensuring
each derived class implements specific behaviors.
Abstract Classes vs. Interfaces

Abstract Class Interface

Can have both abstract and non-abstract All methods are abstract (in some
methods languages)

Can have member variables No member variables (in most languages)

Can have constructors No constructors

Supports single inheritance (C++) Supports multiple inheritance (Java, C#)


Example of an Abstract Class (C++)
Output
Example of an Abstract Class (Java)
Output
Abstract Methods
● An abstract class may contain abstract methods, which have no body.
● These methods must be implemented by any non-abstract subclass.
Example of Abstract Method Implementation (Java)
Output
Key Points to Remember
1. Cannot instantiate abstract classes.
2. Used to provide a base structure for other classes.
3. Subclasses must implement all abstract methods.
4. Abstract classes can have both abstract and concrete methods.
When to Use Abstract Classes?
● When you have a base class that should not be instantiated but share common
functionality with derived classes.
● When you want to enforce a contract for derived classes.
● Ideal for defining common behavior in a hierarchy but leaving implementation details
to subclasses.
Summary
● Abstract classes are blueprints for other classes.
● They provide structure and enforce that subclasses implement specific methods.
● Cannot instantiate abstract classes directly.
● Great for code reuse and ensuring subclasses follow a certain design.
Immutable Classes
(A Deep Dive into Object Immutability in Programming)
What is an Immutable Class?
Definition:

● An Immutable Class is a class whose objects cannot be modified once created.

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:

1. Thread-Safety: Immutable objects are inherently thread-safe, reducing complexity in


concurrent programming.
2. Simplicity: They have fewer potential states, making reasoning about the code
simpler.
3. Caching: Immutable objects can be cached and reused without fear of modification.
4. Predictability: No side effects from hidden state changes.
Common Examples of Immutable Classes
Java Examples:

● 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.

Other Language Examples:

● Python: Tuples are immutable.


● C#: Strings are immutable.
How to Create an Immutable Class (Java Example)
Conti.,
Key Points:

● The class is declared final.


● Fields are private and final.
● No setters; only getters.
Common Pitfalls & Considerations
Pitfalls to Watch Out For:

● 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:

● Performance: Creating new objects frequently can have a performance impact in


certain scenarios.
Conclusion
Summary:

● Immutable classes provide safety, simplicity, and predictability.


● They are an essential concept for building reliable, maintainable, and thread-safe code.
● Use them wisely, especially when thread-safety and consistency are important.
Object Class in Java
(The Root Class of All Java Classes)
What is the Object Class?
Definition:

● 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:

● It's defined in java.lang.Object.


● Provides common methods that are inherited by all Java classes.
Importance of the Object Class
Why is the Object Class Important?

● 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

Definition: public String toString()


● Provides a string representation of the object.
Default Behavior:
● The default implementation in Object returns the class name followed by the object's
hash code (e.g., Person@4e25154f).
Common Override Example:
@Override
public String toString() {
return "Person{name=" + name + ", age=" + age + "}";
}
equals() Method in Detail

Definition: public boolean equals(Object obj)


● Used to compare two objects for equality.

Default Behavior:

● The default implementation checks if the two object references point to the same memory location.

Custom Override Example:


hashCode() Method in Detail

Definition: public int hashCode()


● Returns an integer hash code for the object.

Relationship with equals():

● Objects that are equal according to equals() must have the same hash code.

Override Example:

@Override

public int hashCode() {

return Objects.hash(name, age);

}
clone() Method in Detail

Definition: protected Object clone() throws CloneNotSupportedException


● Creates a copy of the object (shallow copy by default).

Default Behavior:

● Performs a shallow copy by copying field values directly.


● Classes must implement the Cloneable interface to support cloning.
Other Methods in the Object Class
Other Notable Methods:

● 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:

● Sorting collections (e.g., lists, arrays).


● Checking equality (e.g., for duplicates in sets).
● Implementing business rules (e.g., sorting by age, salary, etc.).
The equals() Method

Definition: public boolean equals(Object obj)


● Purpose: Compares two objects for equality.
● Default Behavior: The default equals() method compares memory addresses (reference comparison).

Custom Implementation:

● Typically overridden to compare object fields for logical equality.

Example: @Override

public boolean equals(Object obj) {

if (this == obj) return true;

if (obj == null || getClass() != obj.getClass()) return false;

Person person = (Person) obj;

return age == person.age && name.equals(person.name);

}
The hashCode() Method (Connection with equals())

Definition: public int hashCode()


● Purpose: Returns an integer hash code used in hash-based collections like HashMap and HashSet.

Key Rule:

● Objects that are equal (equals() == true) must have the same hashCode().

Override Example:

@Override

public int hashCode() {

return Objects.hash(name, age);

}
The Comparable Interface

Purpose:

● Defines the natural ordering of objects.

Method Signature:

public int compareTo(T obj)

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

Example: public class Person implements Comparable<Person> {


private String name;
private int age;
@Override
public int compareTo(Person other) {
return Integer.compare(this.age, other.age); // Compare by age
}
}
Usage in Collections:

● When a class implements Comparable, objects can be sorted using Collections.sort() or Arrays.sort().
The Comparator Interface

Purpose:

● Defines custom ordering of objects.

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

Example: public class PersonNameComparator implements Comparator<Person> {

@Override

public int compare(Person p1, Person p2) {

return p1.getName().compareTo(p2.getName()); // Compare by name

Usage in Collections:

● A Comparator can be passed to methods like Collections.sort() or Arrays.sort().


When to Use Comparable vs Comparator
Comparable:

● Use when a single natural ordering is needed.


● Typically used for intrinsic object comparison (e.g., numeric or lexicographical
ordering).

Comparator:

● Use when you need multiple or custom ordering strategies.


● Useful when sorting by different criteria (e.g., by age, by salary, by name).
Example – Sorting with Comparable and Comparator
Comparable Example: Collections.sort(personList); // Uses Person’s compareTo() method

Comparator Example: Collections.sort(personList, new PersonNameComparator()); // Sort


by name

Output:

● Comparable: Sorts by age (default).


● Comparator: Sorts by name (custom).
Conclusion
Summary:

● The equals() method defines object equality.


● The Comparable interface allows defining a natural ordering.
● The Comparator interface provides custom comparison strategies.

You might also like