0% found this document useful (0 votes)
0 views

Chapter4-Inheritance

The document discusses inheritance in object-oriented programming (OOP), highlighting its importance in creating hierarchical relationships between classes, promoting code reuse, and allowing subclasses to extend or modify superclass features. It outlines various types of inheritance, including single, multilevel, multiple, and hierarchical inheritance, and explains the roles of superclasses and subclasses. Additionally, it covers access modifiers in Java, constructors, and their significance in object creation and initialization.

Uploaded by

mageeditz24
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)
0 views

Chapter4-Inheritance

The document discusses inheritance in object-oriented programming (OOP), highlighting its importance in creating hierarchical relationships between classes, promoting code reuse, and allowing subclasses to extend or modify superclass features. It outlines various types of inheritance, including single, multilevel, multiple, and hierarchical inheritance, and explains the roles of superclasses and subclasses. Additionally, it covers access modifiers in Java, constructors, and their significance in object creation and initialization.

Uploaded by

mageeditz24
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/ 30

Dire Dawa University Institute of Technology (DDUIoT)

College of Electrical and Computer Engineering (CECE)

Course: Object Oriented Programming [ECEg-2101]

Chapter Four: Inheritance


Prepared by: Haftu M & Bekalu M.
Introduction 4/4/2025

Inheritance is a fundamental concept in object oriented programming that


allows classes to inherit properties (fields and methods) from other classes.

It enables the creation of hierarchical relationships between classes, where a


subclass inherits the characteristics of its superclass.

Inheritance promotes code reuse and enables the creation of more specialized
classes based on existing classes.

The superclass serves as a template or blueprint for creating subclasses, which


can add new features or modify existing ones.

By BM
2
Introduction 4/4/2025

In procedural programming, data and operations on the data are separate.

Object-oriented programming places data and the operation that pertain to


them within a single entity called an Object.

The object-oriented programming approach organizes in a way that mirrors


the real world, in which all objects are associated with both attributes and
activities.

Object-oriented programming (OOP) involves programming using objects.

OOP Chapter 3 [by Haftu M. & Bekalu M.] 3


Introduction 4/4/2025

In procedural programming, data and operations on the data are separate.

Object-oriented programming places data and the operation that pertain to


them within a single entity called an Object.

The object-oriented programming approach organizes in a way that mirrors


the real world, in which all objects are associated with both attributes and
activities.

Object-oriented programming (OOP) involves programming using objects.

OOP Chapter 3 [by Haftu M. & Bekalu M.] 4


Inheritance 4/4/2025

In procedural programming, data and operations on the data are separate.

Object-oriented programming places data and the operation that pertain to


them within a single entity called an Object.

The object-oriented programming approach organizes in a way that mirrors


the real world, in which all objects are associated with both attributes and
activities.

Object-oriented programming (OOP) involves programming using objects.

OOP Chapter 3 [by Haftu M. & Bekalu M.] 5


Benefits of Inheritance 4/4/2025

 Promotes code reuse, reducing redundancy.

 Enables creation of specialized classes based on existing ones.

 Superclass serves as a template or blueprint for subclasses.

 Subclasses can add new features or modify existing ones.

Functionality of Inheritance

 New classes (derived classes) are created from existing ones.

 Base classes (ancestor classes) provide attributes and behaviors to derived classes.

 Helps simplify programming by reusing existing code with minimal modifications.

OOP Chapter 3 [by Haftu M. & Bekalu M.] 6


Inheritance 4/4/2025

Inheritance also embodies the Is-A relationship. This is easier to understand with
real-world examples. For instance, “A Dog is an Animal” makes sense, with
'Animal' being the parent class and 'Dog' as the child class. You can visualize
this idea through a diagram that illustrates how inheritance works in practice.

OOP Chapter 3 [by Haftu M. & Bekalu M.] 7


Inheritance example
class Animal { class Test{

public String name; public static void main(String[] args) {

public int age; //create an object of the child class

public void eat(){ Dog dog =new Dog();


//accessing properties of the parent class
System.out.println("Animal is eating...");
dog.name="Pappy";
}
dog.age=8;
}
//accessing properties of the own child class
//inherit from Animal
dog.barkSound="Yappy";
class Dog extends Animal{ //extends is a keyword
dog.display();
public String barkSound;
dog.bark();
public void bark(){
// call the method in parent class using child class object
System.out.println("Dog is barking...");
dog.eat();
} }
// Display dog-specific properties. }
public void display(){

System.out.println("Name: "+name+"\n Age: "+age);

}}
4/4/2025
OOP Chapter 3 [by Haftu M. & Bekalu M.] 8
Types of inheritance
There are different types of Single Inheritance:
• Single inheritance is a type of inheritance by which
inheritance, the commonly
A single child class extends from only a single
used types of inheritance are:
parent class. The diagram shown below illustrates
Single Inheritance a single inheritance, Class A is the parent class and

Multilevel Inheritance the Class B is the child class, where Class B only
extends from Class A.
Multiple Inheritance

Hierarchical Inheritance

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 9


Multilevel Inheritance:
 Multilevel inheritance, as illustrated in the following diagram, is a type of inheritance by
which one class can inherit from a child class, and that child class becomes the parent class
for the new class. The figure shows that Class A is the direct parent of Class B and the
indirect parent of Class C, which makes it multilevel inheritance. Class B is subclass of Class
A and parent of Class C. Class C can be considerd as grand child of Class A

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 10


Multiple Inheritance:
 Multiple inheritance is a type of inheritance by which a single child class extends from
multiple parent classes. See the following figure for illustration. The figure shows that Class D
has been extended from Class A, Class B, and Class C actually, java doesn't allow multiple
inheritance, but it implements it through interface implementation, which you will cover in
the coming chapter

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 11


Hierarchical Inheritance:
 Hierarchical inheritance is a type of inheritance in which more than one child class extends
from a single parent class. The figure below shows that many subclasses can be extended
from a single class . Class a is a parent of three subclasses, which are Class B, Class C, and Class
D. Many classes can be extended from a single parent class.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 12


Definition of Super and Sub Classes
 In OOP, the class that is used to create a new class is called the superclass. In other words, the
class from which a subclass inherits its features is referred to as the superclass. It’s also known
as the base class or parent class.

 On the other hand, the class that inherits all the members (fields, methods, and nested
classes) from another class is called the subclass. In simpler terms, a newly created class is a
subclass. It can also be referred to as a derived class, child class, or extended class.

 To inherit from a class, you use the extends keyword. This keyword signifies that the new class
is extending the functionality of an existing class.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 13


Sample java program
Class Vehicle { // The parent class
protected String brand = "Brand001"; // Vehicle attribute
public void xyz() { // Vehicle method
System.out.println("XYZ!");
}}
class Car extends Vehicle {//note the keyword "extends"
private String modelName = "Model001"; // Car attribute
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object
myCar.xyz(); // Call the xyz() method (from the Vehicle class) on the myCar object
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 14


Characteristics of subclasses
 Inheritance: A subclass inherits fields (attributes) and methods (functions) from its superclass, allowing
it to reuse and extend the functionality of the parent class.
 Method Overriding: A subclass can provide a specific implementation for a method that is already
defined in its superclass. This is known as method overriding, enabling the subclass to tailor inherited
methods to fit its specific needs.
 Extensibility: A subclass can introduce new fields and methods that are not present in the superclass.
This allows the subclass to have additional behaviors and attributes that the parent class does not
possess.
 Access Modifier: The access specifiers (public, protected, and private) in the superclass determine the
visibility of its members to the subclass. For example, public members are accessible, protected
members are accessible within the package and subclasses, and private members are not directly
accessible.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 15


Characteristics of subclasses
 Polymorphism: The subclass can be treated as an instance of its superclass. This feature is
called polymorphism, which allows for flexible and dynamic method calls at runtime.

 Relationships: The relationship between a superclass and a subclass is often described as an


"is-a" relationship. For example, if Car is a subclass of Vehicle, then a car "is a" vehicle.

 Subclasses don’t inherit the constructor of the subclass but rather they can invoke using the
super keyword.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 16


Characteristics of subclasses
class Parentclass { class Test {
void m1() { public static void main(String[] args) {
System.out.println("Superclass m1 // Creating an object of subclass.
method"); Childclass c = new Childclass();
// Accessing superclass and subclass members using
} subclass object reference variable.
} c.m1();
class Childclass extends Parentclass { c.m2();
void m2() { }
}
System.out.println("Childclass m2
Output:
method");
Superclass m1 method
} Childclass m2 method
}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 17


Access Modifiers in Java
 Access modifiers, also known as access specifiers, play a crucial role in object-oriented programming
languages. They are essential for controlling the visibility and accessibility of various elements within
your code, such as classes, interfaces, methods, and member variables.

 In Java, access modifiers are keywords that define the scope and visibility of classes, methods,
variables, and constructors. These modifiers help specify where and how the elements of your code
can be accessed, making your code more organized and secure.

 Access modifiers are a fundamental part of object-oriented programming because they enforce
encapsulation, a core principle that restricts direct access to some components of an object. By doing
so, they help protect the integrity of your objects and ensure that their internal workings are hidden
from the outside world, allowing for safer and more manageable code.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 18


Access Modifiers in Java
 Access modifiers play a crucial role in object-oriented programming, shaping how different
parts of a program interact. As mentioned earlier, these special keywords determine the
accessibility of classes, variables, methods, and constructors—essentially acting as gatekeepers
of your code

 By controlling access, modifiers enforce encapsulation, a core principle that safeguards an


object's internal state. This protection not only prevents unintended modifications but also
enhances code maintainability and minimizes potential errors. In essence, access modifiers
help create cleaner, more secure, and well-structured programs, making your code more
reliable and easier to manage.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 19


Access Modifiers in Java
Private:
class Person {
 The private access modifier is the most restrictive
level of access control. private String name;
 When a member (either a field, method, or private String getName() {
constructor) is declared as a private, it can only
return this.name;
be accessed within the same class.

 No other class, including subclasses in the same


}}
package or different packages, can access the  In the above code snippet, the name
member. attribute and the getName() method
 This modifier is typically used for sensitive data
are only accessible within the Person
that should be hidden from external classes.
class.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 20


Access Modifiers in Java
Protected:
class Animal {
 The protected access modifier is less restrictive
protected String type;
than private and default.
protected void displayType() {
 Members declared as protected can be accessed
System.out.println("Type: " + type);
within the same package or in subclasses in
}}
different packages.
In the above code snippet, the type attribute and
 This is particularly useful in cases where you want
the displayType() method can be accessed within all
to hide a member from the world but still make classes in the same package and in any subclass of
it available to child classes.. Animal, even if those subclasses are in different
packages.In the above code snippet, the name
attribute and the getName() method are only
accessible within the Person class.
4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 21
Access Modifiers in Java
Public: The public access modifier is the least
When no access modifier is specified, Java uses a default
restrictive and specifies that the member can be
access level, often called package-private. This means the
accessed from any other class anywhere, whether
member is accessible only within classes in the same
within or in a different package.
package. It is less restrictive than private but more
 This access level is typically used for methods and
restrictive than protected and puclass Dam {// default
variables that must be available consistently to
access modifier
all other classes.
void display() {
class Sum {
System.out.println("Displaying log information");
public int add(int num1, int num2) {
}}
return num1 + num2;

}}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 22


Java Constructors
 Understanding constructors is key to mastering Java, as they play a vital role in object creation and initialization. These special methods are
automatically invoked when a new object is instantiated, ensuring that its instance variables are properly assigned right from the start.
 One of the most powerful aspects of constructors is their ability to initialize data and define the state of an object, making them essential
for maintaining consistency across different class methods. Since every object in Java is created using the new() keyword, at least one
constructor is invoked when an object of a class is instantiated.
 By leveraging constructors effectively, you can write cleaner, more efficient code while ensuring that each object is properly set up before
being used within your program.
Syntax:
//Constructors in java
public class MyClass {
// Constructor
public MyClass() {
// Initialization code goes here
}
// Other methods and variables can be defined here
}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 23


Java Constructors Vs. Java Methods
 Constructors must have the same name as the class within which it is defined it is not necessary for
the method in Java.
 Constructors do not return any type while method(s) have the return type or void if does not return
any value.
 Constructors are called only once at the time of object creation while method(s) can be called any
number of times.
Rules for creating Java constructor
 The constructor name must be the same as its class name.
 A constructor must have no explicit return type.
 A Java constructor cannot be abstract, static, final, and synchronized.
 We can use access modifiers like private, protected, public or default while declaring a constructor in Java.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 24


Java Constructors Vs. Java Methods
 In Java, constructors can be divided into three class Main {
types: int a;
 No-Arg Constructor boolean b;
 Parameterized Constructor public static void main(String[] args) {
 Default Constructor // calls default constructor

Java Default Constructor Main obj = new Main();

 If you do not create any constructor, the Java System.out.println("Default Value:");


compiler automatically creates a no-arg type System.out.println("a = " + obj.a);
constructor during the execution of the program. System.out.println("b = " + obj.b);
This constructor is called the default constructor. }}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 25


Java Constructors Vs. Java Methods
 Similar to methods, a Java constructor may or may not have parameters (arguments). If a constructor does not accept any parameters, it is known
as a no-argument constructor, no-arg constructor in short.
class Company {
String name;
public Company() { // public constructor
name = "DDU and ASU";
}}
class Main {
public static void main(String[] args) {
Company obj = new Company(); // object is created in another class
System.out.println("Company name = " + obj.name);
}}
 Output: DDU and ASU
 In the above example, we have created a constructor Company(). Here, the constructor does not accept any parameters. Hence, it is known as a
no-arg constructor.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 26


Java Parametrized Constructors
 Constructor with arguments is called parameterized
constructor. Let’s look at the example of Output
parameterized constructor in Java. Java is OOP language!
class Main {
Python is OOP language!
String languages
// constructor accepting single value C++ is OOP language!
Main(String lang) {  In the above example, we have created a constructor
languages = lang;
named Main(). The constructor takes a single parameter
System.out.println(languages + " is OOP language!");}
public static void main(String[] args) {
and we are passing the single value to the constructor.
// call constructor by passing a single value Based on the argument passed, the language variable is
Main obj1 = new Main("Java"); initialized inside the constructor.
Main obj2 = new Main("Python");
Main obj3 = new Main("C++");}
}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 27


What is Super Keyword?
 In simpler terms, the super keyword in Java is used to refer to the immediate parent class of a
subclass. It is commonly used to access parent class methods and constructors, enabling a subclass to
inherit and reuse the functionality of its superclass.
 It provides a way to access and call members (methods, variables, and constructors) of the superclass
within the subclass.
 When a class extends another class, the subclass inherits all the non-private members of the
superclass.
 The inherited members can be accessed using the super keyword.
 Usage: the super keyword can be used in three primary contexts:
 To call the superclass constructor.
 To access a method from the superclass that has been overridden in the subclass.
 To access a field from the superclass when it is hidden by a field of the same name in the subclass.

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 28


What is Super Keyword?
 Syntax:

 super();-> to call superclass constructor


 super.methodName();-> to call superclass methods
 super.fieldName;-> to call superclass field
 Constructor Chaining: use super() in the constructor of a subclass to ensure that the constructor of the superclass is called, enabling proper initialization of the
object.
class Animal {
Animal() {
System.out.println("This is Animal class constructor!!");}}
class Dog extends Animal {
Dog() {
super(); // Calls the constructor of Animal class
System.out.println("This is Dog class constructor!!");
}}
class TestSuper {
public static void main(String[] args) {
Dog d = new Dog();}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 29


Editing: How to access superclass method ?
 Method Overriding: use super.methodName() to call a class DogChild extends AnimalSuper {

method from the superclass when it is overridden in the void sound() {


subclass. This is useful for extending or modifying the super.sound(); // Calls the sound() method of Animal class
behavior of the inherited method. System.out.println("Students, this is the overridden sound
 We can access superclass method as follows: method.");
class AnimalSuper { }}
void sound() { class TestSuperMethod {
System.out.println("Students, this is the sound method in Animal public static void main(String[] args) {
super class"); DogChild d = new DogChild();
}} d.sound();
}
}

4/4/2025 OOP Chapter 3 [by Haftu M. & Bekalu M.] 30

You might also like