[go: up one dir, main page]

0% found this document useful (0 votes)
35 views29 pages

Chap2 Inheritance

Chapter 2 of the Advanced Programming course focuses on Object Oriented Programming with an emphasis on inheritance, explaining its importance for code reusability, extensibility, and hierarchical organization. It covers key concepts such as base and derived classes, method overriding, types of inheritance, and best practices through practical exercises. The chapter concludes with a discussion on the benefits of inheritance and introduces the concept of composition as an extension.

Uploaded by

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

Chap2 Inheritance

Chapter 2 of the Advanced Programming course focuses on Object Oriented Programming with an emphasis on inheritance, explaining its importance for code reusability, extensibility, and hierarchical organization. It covers key concepts such as base and derived classes, method overriding, types of inheritance, and best practices through practical exercises. The chapter concludes with a discussion on the benefits of inheritance and introduces the concept of composition as an extension.

Uploaded by

xvjtfy947p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Advanced Programming

CO2039

Chapter 2: Object Oriented Programming


Revision - Inheritance

ĐẠI HỌC QUỐC GIA THÀNH PHỐ HỒ CHÍ MINH


TRƯỜNG ĐẠI HỌC BÁCH KHOA
TP.HCM, 03/01/2025
CONTENT
01 INTRODUCTION TO INHERITANCE

02 KEY CONCEPTS OF INHERITANCE

03 HOW INHERITANCE WORKS?

04 BEST PRACTICES

05 CONCLUSION

06 EXTENSION: COMPOSITION

2
Additional Notes

Call constructor of the superclass

Default baseclass

Class Object

Overloading method

Subclass inherits ALL


members of the superclass

3
INTRODUCTION TO
01 INHERITANCE

4
What is Inheritance?
A mechanism for creating a new class (called a derived class or child
class) from an existing class (called a base class or parent class) to reuse
and extend its functionality.

5
Why is Inheritance important?
● Code Reusability: Reuse of common logic
from base classes ⇒ codebase more efficient
and maintainable.
● Extensibility: New features can be added by
extending the base class ⇒ easy updates
without affecting existing code.
● Polymorphism: Introduced in Chap 3 later.
● Hierarchical Organization: Classes can be
organized in a logical structure, representing
real-world relationships.
6
KEY CONCEPTS OF
02 INHERITANCE

7
Base class & Derived class
Base class (Parent/Superclass): The class whose properties (attributes)
and methods (functions) are inherited by another class.
Example: Animal is a base class.
Derived class (Child/Subclass): The class
inheriting from the base class. It can use or
override the members of the base class
and add its own ⇒ “is-a” relationship
Example: Dog inherits from Animal ⇒ Dog
“is-a” Animal.

8
Method overriding
A derived class can redefine (override) a method from the base class to
provide specific functionality.
● The method in the base class must have the same name, return
type, and parameters as the overridden method.
Constructors: When an object of a derived class is created, the base
class constructor is called first, followed by the derived class constructor.

Destructors: When an object is destroyed, the derived class destructor


is called first, followed by the base class destructor.

Introduced more detailed in Chap 3 - Polymorphism 9


Types of Inheritance

Single Inheritance: A derived class inherits from one base class.


Multiple Inheritance: A class inherits from more than one base class.
(Supported in C++ but not in Java)
Multilevel Inheritance: A class inherits from a derived class, forming a
chain.
Hierarchical Inheritance: Multiple derived classes inherit from one base
class.
Hybrid Inheritance: A combination of two or more types of inheritance.

10
Types of Inheritance

Diamond
Problem?

11
HOW INHERITANCE
03 WORKS?

12
Subclass inherits all members from Superclass

When a subclass inherits from a superclass:


● All members of the superclass, whether public or private, are
technically inherited.
● However, accessibility depends on the access specifier:
○ Public and protected members can be directly accessed in the
subclass.
○ Private members are inherited but not accessible directly; they
are accessible through public or protected getters and setters in
the superclass.

13
Subclass inherits all members from Superclass

14
Pointers for Polymorphism (1)
class Superclass {
public:
virtual void display() { cout << "Superclass\n"; }
}; Superclass Subclass

class Subclass : public Superclass {


public:
void display() override { cout << "Subclass\n"; }
}; sup sub

int main() {
Subclass sub;
Superclass sup = sub;
sup.display(); // Output: ???
}

15
Pointers for Polymorphism (2)
class Superclass {
public:
virtual void display() { cout << "Superclass\n"; }
}; Superclass Subclass

class Subclass : public Superclass {


public:
void display() override { cout << "Subclass\n"; }
}; sup sub

int main() {
Subclass sub;
Superclass* sup = &sub;
sup–>display(); // Output: ???
}

16
Implicit use of pointers
class Superclass {
public void display() {
System.out.println("Superclass");
}
}
class Subclass extends Superclass { In Java (and many other OOP
@Override
public void display() {
languages): All objects are accessed via
System.out.println("Subclass"); references (similar to pointers in C++).
}
}
public class Main {
public static void main(String[] args) {
Superclass obj = new Subclass();
obj.display(); // Output: ???
}
} 17
04 BEST PRACTICES

18
Exercise 1 - Inheritance in Vehicle classes (1)

Create a base class Vehicle with the following private attributes:


● brand (string)
● year (int)
Add the following to Vehicle:
● A default constructor that sets default values ("Unknown" for brand, 0 for
year).
● A parameterized constructor to initialize brand and year.
● Setters and getters for brand and year.
● A method displayInfo() to print details of the vehicle.

19
Exercise 1 - Inheritance in Vehicle classes (2)
Create a derived class Car that inherits from Vehicle:
● Add a private attribute: model (string).
● Provide a default constructor and a parameterized constructor for Car using
constructor chaining.
● Override the displayInfo() method to include model.
Create another derived class Bike that inherits from Vehicle:
● Add a private attribute: engineCapacity (int).
● Provide constructors and override displayInfo() to include engineCapacity.
In the main function:
● Create a Car object using both default and parameterized constructors and display its
details.
● Create a Bike object using both default and parameterized constructors and display its
details.
20
Exercise 2 - Enhanced Library System with Inheritance (1)
Book Class (Base Class):
● Attributes: title, author, ISBN, price, and stock.
● Methods:
○ Constructor to initialize attributes.
○ Getter and setter methods.
○ A virtual displayDetails() method to display book information.
Derived Classes:
● EBook (inherits Book):
○ Additional attribute: fileSize (in MB).
○ Override displayDetails() to include file size.
● PrintedBook (inherits Book):
○ Additional attribute: pageCount.
○ Override displayDetails() to include page count.

21
Exercise 2 - Enhanced Library System with Inheritance (2)
Library Class:
● Attributes:
○ A dynamic array or vector of pointers to Book objects (supporting both EBook
and PrintedBook).
● Methods:
○ addBook(Book*): Add a new book (of any type).
○ searchByTitle(string) and searchByAuthor(string): Search books by title/author.
○ borrowBook(string ISBN): Reduce stock of the specified book by 1.
○ displayAllBooks(): Display all books in the library.
Main Function:
● Add a mix of EBook and PrintedBook objects to the library.
● Simulate user operations: Search for books by title/author, Borrow books, Display all
books.
22
Exercise 3 - Point2D and Point3D

Can you write a program


based on this class diagram?

23
05 CONCLUSION

24
Conclusion

1. Inheritance is a fundamental concept of OOP, enabling the creation of new


classes by reusing and extending existing ones.
2. The primary benefit of inheritance lies in code reuse and the establishment
of hierarchical relationships between classes.
3. Method overriding and dynamic binding1 are key mechanisms in
inheritance, supporting polymorphism and enhancing flexibility in design.

1
Introduced in Chap 3 - Polymorphism 25
EXTENSION:
06 COMPOSITION

26
OOP Composition

Complete this code: https://www.programiz.com/online-compiler/03auquyMRJCj0

27
Hands-on exercise

Complete this code: https://www.programiz.com/online-compiler/74XUfgm8cwc0G

28
Thank you for your
attention!
https://www.cse.hcmut.edu.vn

ĐẠI HỌC QUỐC GIA THÀNH PHỐ HỒ CHÍ MINH


TRƯỜNG ĐẠI HỌC BÁCH KHOA

You might also like