0% found this document useful (0 votes)
4 views13 pages

Java Inheritance Lecture Notes

This document provides an overview of inheritance in Java, explaining its importance in avoiding code duplication and enhancing code reusability. It covers key concepts such as the extends keyword, superclass and subclass terminology, and the rules of inheritance, including the limitations of single inheritance. Practical examples and a case study illustrate how to implement inheritance effectively in Java programming.

Uploaded by

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

Java Inheritance Lecture Notes

This document provides an overview of inheritance in Java, explaining its importance in avoiding code duplication and enhancing code reusability. It covers key concepts such as the extends keyword, superclass and subclass terminology, and the rules of inheritance, including the limitations of single inheritance. Practical examples and a case study illustrate how to implement inheritance effectively in Java programming.

Uploaded by

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

Java — Chapter 10

Inheritance in Java
Object-Oriented Programming | Lecture Notes

1. Introduction
This lecture covers Chapter 10 of Java, focusing on Inheritance. We begin from Section 8 of the
chapter. The following topics are covered in this lecture:
• What is inheritance in Java?
• Why inheritance is useful — avoiding code duplication.
• How to declare and use inheritance using the extends keyword.
• Super class and subclass terminology.
• Access modifiers and what gets inherited.
• Practical code demonstration with Base and Derived classes.
• Important rules of inheritance in Java (single inheritance only).

Note to Students
Before starting this chapter, make sure you have completed the previous videos in this Java
playlist (up to Video #45).
All lecture notes for this chapter are available for free on the course website once the
chapter ends.

2. What is Inheritance?
2.1 The Real-World Analogy
In the real world, children inherit features from their parents and grandparents. For example,
your eyes might look like your father's, while your other features resemble your mother's. These
traits flow naturally down through generations: grandfather → father → you.

Real-World Example
Grandfather has certain traits.
Father inherits some of those traits from grandfather.
You (the child) inherit traits from your father.

In the same way, a child class in Java inherits properties and methods from a parent class.
2.2 Inheritance in Java
In Java, inheritance allows a new class (the child/subclass) to carry forward the properties and
methods of an existing class (the parent/superclass). This is a core principle of Object-Oriented
Programming.

Definition
Inheritance is used to inherit (reuse) properties and methods from an existing class.
You can make more advanced changes in the new class, or add entirely new features to it,
without needing to rewrite the code that already exists in the parent class.

3. Why Use Inheritance?


3.1 Avoiding Code Duplication — Don't Reinvent the Wheel
Suppose you have already created a class called Base with certain properties and methods.
Now you want to create another class, Derived, that does everything Base does, plus a few
extra things.

Without inheritance, you would have to copy and paste all the code from Base into Derived. This
causes two major problems:
• You write the same code twice — wasteful and hard to maintain.
• If you change something in Base (for example, modifying a setter method), you have to
remember to make the same change in Derived as well. If you forget, your code
becomes inconsistent.

Reinventing the Wheel


The phrase 'reinventing the wheel' means doing something again that has already been
done.
The wheel was invented long ago — you don't need to invent it again.
Instead, focus on improving what already exists.

In programming: if a class already exists with the logic you need, reuse it via inheritance.
Don't rewrite the same code — take the existing 'wheel' and build your vehicle on top of it.

3.2 The Smartphone Analogy

Analogy — Phone vs Smartphone


Suppose a Phone class already exists with basic calling features.
You want to create a Smartphone, which has everything a Phone has, PLUS:
• Camera
• Music system
• YouTube video streaming
• Photo editing

Instead of rewriting the Phone features, you extend the Phone class and only
add the new Smartphone-specific features.

Smartphone extends Phone ← Java syntax

Phone = superclass (parent / base class)


Smartphone = subclass (child / derived class)

4. Terminology
Java uses several names to refer to the two sides of an inheritance relationship. All of these
mean the same thing:

Role Alternative Names


Parent class Super class | Base class | Parent
Child class Sub class | Derived class | Child | Extended class

Example — Terminology in Context


class Base { ... } ← superclass / parent / base class
class Derived extends Base { } ← subclass / child / derived class

Base is the father. Derived is the son/daughter.


Derived has everything Base has, plus its own additions.

5. Declaring Inheritance in Java


5.1 The extends Keyword
Inheritance in Java is declared using the extends keyword. The syntax is:
Syntax:
class SubClass extends SuperClass {
// additional fields and methods
}

Once you write extends, everything that exists in the superclass becomes available in the
subclass. Whether it can actually be accessed depends on the access modifier of each member
— but it is all inherited.

5.2 Live Coding Example — Base and Derived Classes


Step 1: Create the Base Class
A Base class is created with the following members:
• A field: int x
• A constructor that prints a message (e.g., 'I am constructor')
• A method: void printMe() — prints a message
• Getter and setter: getX() and setX()

// [Link]
public class Base {
public int x;

public Base() {
[Link]("I am constructor");
}

public void printMe() {


[Link]("I am Base");
}

public int getX() { return x; }


public void setX(int x) { this.x = x; }
}

Step 2: Create the Derived Class Using extends


A Derived class is created that extends Base and adds its own field y with its own getter and
setter:

// [Link]
public class Derived extends Base {
public int y;

public int getY() { return y; }


public void setY(int y) { this.y = y; }
}

What Derived Inherits from Base


• Field: int x (from Base)
• Method: printMe() (from Base)
• Methods: getX(), setX() (from Base)
• Constructor behaviour of Base

Plus its own: int y, getY(), setY()

6. Code Demonstration — Objects and Access


6.1 Creating a Base Object

// In main method:
Base b = new Base();
[Link](4);
[Link]([Link]()); // Output: 4

This works as expected. The Base class has x, setX(), and getX(), so everything compiles and
runs.

6.2 Creating a Derived Object — Accessing Base Members

// In main method:
Derived d = new Derived();
[Link](3); // inherited from Base
[Link]([Link]()); // Output: 3 (inherited from Base)
[Link](7); // Derived's own method
[Link]([Link]()); // Output: 7

Because Derived extends Base, the object d can use all the public members of Base, as well as
its own new members.
6.3 What Base Cannot Access from Derived

// This will NOT compile:


Base b = new Base();
[Link](5); // ERROR — setY() is not in Base
[Link](); // ERROR — getY() is not in Base

Compiler Error Explained


Base class only has x. It has no knowledge of y, setY(), or getY().
If you try to call these on a Base object, the compiler says: 'What are you doing?'
These methods simply do not exist in Base.

Question for students: Can you use setY() and getY() on a Derived object?
Answer: YES — because y, setY(), and getY() are defined inside Derived itself.
7. Inheritance and Automatic Change Propagation
One of the most powerful benefits of inheritance is that any change made to the Base class
automatically reflects in the Derived class.

Example 7.1 — Change Propagation


Suppose you modify the getX() method in Base to print a message before returning the
value:

public int getX() {


[Link]("Getting x from Base...");
return x;
}

Now, when you call [Link]() on a Derived object, it will AUTOMATICALLY use this
updated version — because Derived inherits getX() from Base.

You did NOT have to touch the Derived class at all.

This is the key advantage over copy-paste: update the parent once, and all children
automatically benefit.

8. More Examples of Inheritance


8.1 Class Hierarchy Examples
Superclass (Parent) Subclass (Child) — what is added
Animal Dog — adds bark(), breed field
Animal Cat — adds meow(), colour field
Vehicle Truck — adds payload capacity, axle count
Phone Smartphone — adds camera, music, video streaming,
photo editing

Example 8.1 — Animal → Dog, Cat

class Animal {
String name;
void eat() { [Link](name + " is eating"); }
void sleep() { [Link](name + " is sleeping"); }
}

class Dog extends Animal {


void bark() { [Link](name + " says: Woof!"); }
}

class Cat extends Animal {


String colour;
void meow() { [Link](name + " says: Meow!"); }
}

// Both Dog and Cat automatically have eat() and sleep() from Animal.
// They only define what makes them unique.

Practice Task for Students

Student Exercise
Create a class Animal with the following:
• A name field
• A method: speak() that prints a generic message

Then create a class Dog that extends Animal and adds:


• A method: bark() that prints 'Woof! Woof!'

Create objects of both classes in main() and test them.


Can a Dog object call speak()? Can an Animal object call bark()?

9. What Gets Inherited — and What Does Not


9.1 What a Subclass Inherits
A subclass inherits the following from its superclass (subject to access modifiers):
• All public and protected fields.
• All public and protected methods.
• Any default (package-private) members, if both classes are in the same package.

9.2 What a Subclass Does NOT Inherit


• Private variables and private methods — these are NOT accessible in child classes.
• Constructors — constructors are not inherited (though they can be called using super()).
Access Modifier Rule of Thumb (for now)
As long as a member is declared public in the superclass, it will be accessible in the
subclass.

Private members of the superclass exist in memory but cannot be accessed directly from
the subclass.
The full access modifier rules (public, protected, default, private) will be covered in
upcoming videos.

10. Single Inheritance in Java


Java supports only single inheritance for classes. This means a subclass can extend only one
superclass at a time. You cannot have two parent classes.

// VALID — single inheritance:


class Derived extends Base { }

// INVALID — Java does NOT support multiple inheritance for classes:


class Derived extends Base1, Base2 { } // Compile error!

Why No Multiple Inheritance?


Multiple inheritance can create ambiguity (the 'Diamond Problem') — if two parent classes
have a method with the same name, the compiler doesn't know which one to use.

Java solves this by allowing multiple inheritance only through interfaces (not classes).
Interfaces will be covered in a later chapter.
11. Case Study — Building a Class Hierarchy for a School
System
11.1 Problem Statement

Case Study: School Management System

A school needs to model three types of people: Person, Student, and Teacher.

Every Person has: name, age, and a method introduce() that prints their name.

A Student IS a Person, and additionally has: rollNumber, and a method study().

A Teacher IS a Person, and additionally has: subject, and a method teach().

Design the class hierarchy using inheritance.

11.2 Solution

// Step 1: Define the superclass


public class Person {
public String name;
public int age;

public void introduce() {


[Link]("Hi, I am " + name + ", age " + age);
}
}

// Step 2: Student extends Person


public class Student extends Person {
public int rollNumber;

public void study() {


[Link](name + " is studying.");
}
}

// Step 3: Teacher extends Person


public class Teacher extends Person {
public String subject;
public void teach() {
[Link](name + " teaches " + subject);
}
}

// Step 4: Use the classes in main()


public class Main {
public static void main(String[] args) {
Student s = new Student();
[Link] = "Ravi";
[Link] = 20;
[Link] = 101;
[Link](); // inherited from Person → 'Hi, I am Ravi, age 20'
[Link](); // Student's own method → 'Ravi is studying.'

Teacher t = new Teacher();


[Link] = "Mrs. Sharma";
[Link] = 40;
[Link] = "Mathematics";
[Link](); // inherited from Person
[Link](); // Teacher's own method
}
}

11.3 What This Demonstrates


• Person is the superclass. Student and Teacher are both subclasses.
• Both Student and Teacher automatically get name, age, and introduce() from Person.
• Neither Student nor Teacher had to re-declare those fields or re-implement introduce().
• Each subclass only adds what is unique to it.
• If you change introduce() in Person, both Student and Teacher automatically get the
updated version.
• A Person object cannot call study() or teach() — those only exist in the subclasses.

12. Important Notes and Reminders


12.1 Notes on This Lecture
• All code demonstrated in this lecture should be typed out and run by students.
• The notes for this chapter are available for free on the course website as soon as the
chapter ends.
• Do not pay anyone for these notes — they are provided free of charge.
• If you see anyone selling these notes or course materials, please be aware that this is
not authorised.

12.2 What Is Coming Next


• Access modifiers in detail: public, private, protected, default — and how they affect
inheritance.
• The super keyword — calling the parent's constructor and methods from the child class.
• Method overriding — when a child class redefines a method from the parent.
• Multiple inheritance via interfaces.

13. Summary
13.1 Key Concepts at a Glance
Concept Summary
Inheritance Allows a class to reuse properties and methods of
another class.
extends keyword Used to declare inheritance in Java: class Child extends
Parent
Superclass The parent / base class being inherited from.
Subclass The child / derived class that inherits and may extend.
What is inherited All public and protected members of the superclass.
What is NOT inherited Private members; constructors are also not inherited.
Single inheritance Java classes can extend only ONE superclass.
Change propagation Changes in the superclass automatically affect all
subclasses.

13.2 Step-by-Step: How to Use Inheritance


1. Identify shared features → put them in a superclass.
2. Write the superclass with those fields and methods.
3. For each specialised class, write: class ChildName extends ParentName { }
4. Inside the child class, add only the new fields and methods that are unique to it.
5. Create objects of the child class and access both inherited and new members.

Golden Rule of Inheritance


If a feature is COMMON to multiple classes → put it in the superclass.
If a feature is UNIQUE to one class → put it only in that subclass.

This keeps your code DRY: Don't Repeat Yourself.

You might also like