0% found this document useful (0 votes)
31 views9 pages

OOPS Module 3 Notes

OOPS Module 3 Notes
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)
31 views9 pages

OOPS Module 3 Notes

OOPS Module 3 Notes
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
You are on page 1/ 9

Object Oriented Programming with JAVA – Module 3

MODULE 3
Inheritance:
 Inheritance Basics: Inheritance is a mechanism in OOP that enables a new class to
inherit characteristics (fields and methods) from an existing class.
 It forms a hierarchical relationship between classes, promoting code reuse and
establishing a hierarchy of related classes.
 A class that inherits from another class can reuse the methods and fields of that class.
 In addition, we can add new fields and methods to your current class as well.
Need for Inheritance
 In Java, inheritance serves several important purposes, making it a crucial feature in
object-oriented programming. Some key reasons highlighting the need for inheritance
in Java include:
 Code Reusability:
Elimination of Redundancy: Inheritance allows subclasses to inherit
properties and behaviors from a superclass. This reduces redundant
code by inheriting common attributes and methods from a shared
parent class.
 Enhancing Software Design:
Hierarchy Creation: Inheritance helps in creating a hierarchy of
classes, organizing them in a logical manner based on their
relationships. This promotes a more understandable and maintainable
code structure.
 Extensibility and Maintenance:
Adding New Functionality: Subclasses can extend the functionality of
the superclass by adding new methods or fields without modifying the
original class. This allows for easy extension and modification of code.
 Polymorphism:
Method Overriding: Inheritance facilitates polymorphism, where
subclasses can provide their own implementation of methods inherited from
the superclass. This enables the same method name to behave differently
based on the object it is called upon.
 Flexibility and Modularity:
Customization and Specialization: Subclasses can specialize and
customize behaviors inherited from the superclass to suit specific needs. This
allows for the creation of more specialized and specific classes.
 Software Development Efficiency:
Faster Development: Reusing existing code through inheritance
accelerates the development process by leveraging already established and tested
code.

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

Consider an example where you have a superclass called Vehicle:


class Vehicle {
String brand;
int year;
void start() {
// Common start functionality for vehicles
}
// Other methods and attributes...
}
To the above class we can then create subclasses such as Car, Bike, and Truck that inherit
from the Vehicle class. Each subclass can have its own specialized attributes and methods
while inheriting common functionality from the Vehicle superclass.
class Car extends Vehicle {
int doors; // Additional attributes and methods specific to a Car...
}
Java inheritance promotes code reuse, enhances software design, facilitates extensibility, and
allows for more efficient and modular software development. It forms the backbone of
object-oriented programming paradigms and contributes significantly to building scalable and
maintainable applications.
Consider another example:
// Superclass - Animal
class Animal {
String name;
int age;
// Constructor
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display information
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
// Common method for all animals
public void makeSound() {
System.out.println("Generic animal sound.");
}
}
Now, let's create subclasses for specific types of animals that inherit from the Animal class.
// Subclass - Dog
class Dog extends Animal {
String breed;
// Constructor
public Dog(String name, int age, String breed) {

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

super(name, age); // Calling superclass constructor


this.breed = breed;
}
// Method overriding - Specific sound for dogs @Override
public void makeSound() {
System.out.println("Dog barks!");
}
// Additional method for dogs
public void wagTail() {
System.out.println("Dog wags its tail.");
}
}
// Subclass - Cat
class Cat extends Animal {
boolean isLongHair;
// Constructor
public Cat(String name, int age, boolean isLongHair) {
super(name, age); // Calling superclass constructor
this.isLongHair = isLongHair;
}

// Method overriding - Specific sound for cats @Override


public void makeSound() {
System.out.println("Cat meows!");
}
// Additional method for cats
public void purr() {
System.out.println("Cat purrs softly.");
}
}
Now let us understand the usage:
public class AnimalTest {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy", 3, "Golden Retriever");
Cat myCat = new Cat("Whiskers", 2, true);
// Display information and behaviors of animals
myDog.displayInfo(); // Output: Name: Buddy, Age: 3
myDog.makeSound(); // Output: Dog barks!
myDog.wagTail(); // Output: Dog wags its tail.
myCat.displayInfo(); // Output: Name: Whiskers, Age: 2
myCat.makeSound(); // Output: Cat meows!
myCat.purr(); // Output: Cat purrs softly.
}
}

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

Superclass and Subclass


Inheritance in object-oriented programming involves the creation of a superclass and one or
more subclasses. Let's delve deeper into the concepts of superclass and subclass in
inheritance:
Superclass:
 Definition: A superclass (also known as a base class or parent class) is the existing
class from which other classes inherit properties (attributes and methods).
 Characteristics:
 Contains common attributes, methods, and behaviors shared by its subclasses.
 Serves as a blueprint or template for creating subclasses.
Example:
// Superclass - Animal
class Animal {
// Attributes and methods common to all animals
}
Subclass:
 Definition: A subclass (also known as a derived class or child class) is a class that
inherits properties from its superclass.
 Characteristics:
 Inherits attributes and methods from its superclass.
 Can have its own unique attributes, methods, and behaviors in addition to
those inherited.
Example:
// Subclass - Dog
class Dog extends Animal {
// Inherits attributes/methods from Animal class
// Can have additional attributes/methods specific to dogs
}
Relationship between Superclass and Subclass:
 Inheritance Relationship:
 A subclass extends a superclass using the extends keyword in Java.
 Syntax: class SubclassName extends SuperclassName { /* class body */ }
 Access to Superclass Members:
 Subclasses inherit all visible attributes and methods from the superclass.
 They can use and modify these inherited members unless they are private (not
accessible outside the class).
Example:
Consider an example with a superclass Vehicle and subclasses Car and Bike:
// Superclass - Vehicle
class Vehicle {
// Attributes and methods common to all vehicles
}

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

// Subclass - Car
class Car extends Vehicle {
// Inherits attributes/methods from Vehicle
// Can have additional attributes/methods specific to cars
}

// Subclass - Bike
class Bike extends Vehicle {
// Inherits attributes/methods from Vehicle
// Can have additional attributes/methods specific to bikes
}
Key Points:
 The superclass provides a common set of characteristics to its subclasses.
 Subclasses inherit properties from their superclass and can extend their functionality
by adding new attributes or methods.
 Inheritance establishes an "IS-A" relationship, meaning a subclass "IS-A" type of its
superclass.
Understanding the relationship between a superclass and its subclasses is crucial in
leveraging inheritance to create a hierarchy of related classes and promote code reuse in
object-oriented programming.
Using super
In Java, the super keyword is used to refer to the superclass, primarily within subclasses, and
serves various purposes. Here are the key usages of the super
1. Accessing Superclass Members:
 Accessing Superclass Fields and Methods:
 Allows a subclass to access methods or fields defined in its superclass.
 Helps in cases where a method or field in a superclass is hidden by a similar
member in the subclass.
Example
class Superclass {
int num = 10;
void display() {
System.out.println("Superclass method");
}
}
class Subclass extends Superclass {
int num = 20;
void display() {
System.out.println("Subclass method");
}
void accessSuperclassMembers() {
System.out.println(super.num); // Accessing superclass field
super.display(); // Invoking superclass method
}
}

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

2. Invoking Superclass Constructors:


 Constructor Chaining:
 Enables the subclass constructor to explicitly call a constructor of the
superclass.
 Helps in initializing inherited fields from the superclass.
Example
class Superclass {
Superclass(int value) {
// Superclass constructor logic
}
}

class Subclass extends Superclass {


Subclass(int value) {
super(value); // Invoking superclass constructor
// Subclass constructor logic
}
}
3. Overriding Methods:
 Method Overriding:
 When a method in a subclass overrides a method in the superclass, the super
keyword can be used to explicitly call the superclass method.
class Superclass {
void display() {
System.out.println("Superclass method");
}
}

class Subclass extends Superclass {


@Override
void display() {
super.display(); // Calling superclass method
System.out.println("Subclass method");
}
}
4. Accessing Superclass Constructors and Methods:
 Usage in Inner Class Constructors:
 When an inner class is defined within a subclass, super() can be used to call
the constructor of the immediate outer class.
class OuterClass {
class InnerClass {
InnerClass() {
// Call to superclass constructor using super()
}
}
}

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

5. Usage in Interface Implementations:


 Referencing Interface Methods:
 If a subclass implements an interface and overrides a default method, super
can be used to call the default method implementation provided by the
interface.
interface MyInterface {
default void display() {
System.out.println("Default implementation");
}
}

class Subclass implements MyInterface {


@Override
public void display() {
MyInterface.super.display(); // Calling default method implementation
System.out.println("Subclass method");
}
}
The super keyword in Java plays a crucial role in referencing superclass members,
constructors, methods, and allowing for explicit invocation of superclass functionalities
within a subclass or related context.

Method Overriding
Method overriding is a key concept in object-oriented programming that allows a subclass to
provide a specific implementation for a method that is already defined and declared in its
superclass. It enables the subclass to provide its own version of a method that has the same
name, return type, and parameters as a method in the superclass. Here's a detailed explanation
of method overriding:
Key Points:
Inheritance and Overriding:

 Inheritance is a prerequisite for method overriding. It involves creating a subclass


that extends a superclass.
 When a subclass defines a method that already exists in its superclass, it's called
method overriding.
Rules for Method Overriding:

 Method name, parameters, and return type must be the same in both superclass and
subclass.
 The access modifier of the overriding method should not be more restrictive than the
overridden method (e.g., if the superclass method is public, the overriding method
cannot be private).
 The overridden method in the superclass must not be final, as final methods cannot be
overridden.

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

Example Illustrating Method Overriding:


class Superclass {
void display() {
System.out.println("Superclass display method");
}
}
class Subclass extends Superclass {
@Override
void display() {
System.out.println("Subclass display method");
}
}
1. Usage and Benefits:
 Provides a way to implement runtime polymorphism.
 Allows the subclass to define specific behavior while maintaining a common method
signature.
 Enables the superclass reference to hold subclass objects, leading to dynamic method
dispatch during runtime.
2. Dynamic Method Dispatch:
 In runtime polymorphism, the actual method called is determined by the type of
object at runtime.
 When a method is called using a superclass reference that refers to a subclass object,
the JVM decides which method to execute based on the object's actual type.
Example of Method Overriding:
Let's consider an example using the previously defined Superclass and Subclass:

public class MethodOverrideExample {


public static void main(String[] args) {
Superclass obj1 = new Superclass();
obj1.display(); // Output: "Superclass display method"
Superclass obj2 = new Subclass();
obj2.display(); // Output: "Subclass display method" - Dynamic method dispatch
}
}
In this example:
 obj1 is an instance of Superclass, so it calls the display() method of Superclass.
 obj2 is an instance of Subclass, but it is referred to by a Superclass reference.
However, it calls the overridden display() method in the Subclass due to dynamic
method dispatch.
Method overriding enables subclasses to provide their own implementation of methods
defined in their super classes, facilitating customization and polymorphic behavior in Java
programs.

Dept. of ISE, JSSATE, Bengaluru1


Object Oriented Programming with JAVA – Module 3

Example program for Simple Inheritance


:

class A{
int i,j;
voidshowij(){
Systen.out.println(“ i and j:” + i + “ ” + j);
}
}
class B extends A{
int k;
void showk() {
System.out.println(“k: ” +k);
}
void sum(){
System.out.println(“i+j+k: ” +(i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

Dept. of ISE, JSSATE, Bengaluru1

You might also like