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

07 Inheritance

The document discusses inheritance in object-oriented programming as a way to avoid code redundancy when multiple classes share common attributes and behaviors, by creating a superclass that defines these shared elements and allowing subclasses to extend the superclass to inherit its functionality, thereby only defining unique attributes and behaviors in each subclass. It provides examples of creating employee subclasses that inherit from a superclass to avoid duplicating code for common employee attributes and methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

07 Inheritance

The document discusses inheritance in object-oriented programming as a way to avoid code redundancy when multiple classes share common attributes and behaviors, by creating a superclass that defines these shared elements and allowing subclasses to extend the superclass to inherit its functionality, thereby only defining unique attributes and behaviors in each subclass. It provides examples of creating employee subclasses that inherit from a superclass to avoid duplicating code for common employee attributes and methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Inheritance

Instructor: Dr. Fahed Jubair


The Problem of Code Redundancy
• Imagine you are developing an object-oriented program for a company that has
two types of employees: a programmer and a site engineer
• Below are the classes that represent both employees
• Can you see the problem of code redundancy?

© All rights reserved.


Inheritance
• Classes that share common attributes and behaviors can have redundant
codes
• Inheritance is introduced on objected-oriented programming to solve the
problem of redundancy
• If you have objects A and B with common attributes and behaviors, then
you can apply inheritance as follows:
• Create a new class that encapsulate common attributes and behaviors from, which
we will call the superclass
• Make objects A and B subclasses of the superclass, i.e., A and B will inherit the
functionality ofthe superclass

© All rights reserved.


Creating the Superclass

© All rights reserved.


SuperClasses and SubClasses
• In Java, Inheritance allows creating a superclass (i.e., a general class) and
later allow other subclasses (i.e., specialized classes) to extend it in
order to inherit its functionality
• A superclass is also referred to as the base class or the parent class
• A subclass is also referred to as the derived class or the child class
• What exactly is inherited by subclasses from superclass?
• public attributes and methods can be inherited
• private attributes and methods cannot be inherited
• A superclass can have any number of subclasses
• A subclass can only extend one superclass
© All rights reserved.
Employee Class

Common attributes and behavior

Let us also add toString method

© All rights reserved.


Programmer Class
extends keywords is used
to create inheritance

Superclass constructor is invoked

© All rights reserved.


SiteEngineer Class

© All rights reserved.


Test Class

// output
Employee [name=Asma, salary=100.0]
Programmer [name=Rawan, salary=200.0, product=HR system]
SiteEngineer [name=Amal, salary=200.0, siteLocation=Dubai]

© All rights reserved.


Inheritance
Representation
using UML

© All rights reserved.


The protected Keyword

public class Coffee {


public class Espresso extends Coffee {
protected double price;
public Coffee(){
Protected keyword allows a price = 5.24;
public Coffee(){
subclass to directly access an }
price = 3.44;
}
} attribute of the superclass
}

© All rights reserved.


11.14 The protected Data and Methods 441

Visibility Modifiers in Java


Use the private modifier to hide the members of the class completely so that they cannot
be accessed directly from outside the class. Use no modifiers (the default) in order to allow
the members of the class to be accessed directly from any class within the same package but
not from other packages. Use the protected modifier to enable the members of the class to
• Java has four
be accessed keywords
by the subclasses in to
anydetermine the
package or classes “visibility”
in the same package.of
Useattributes
the public
inside a class
modifier totheother
to enable membersclasses
of the class to be accessed by any class.

TABLE 11.2 Data and Methods Visibility


Modifier Accessed Accessed Accessed from Accessed
on members from the from the a subclass in a from a different
in a class same class same package different package package
public ✓ ✓ ✓ ✓
protected ✓ ✓ ✓ –
default (no modifier) ✓ ✓ – –
private ✓ – – –

package p1;
© All rights reserved.
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
Abstract Classes
• Java allows declaring a class as an abstract class
• Abstract classes cannot be instantiated
• Abstract classes are meant to be superclasses
• Abstract classes can have constructors, which are meant to be used by
subclasses
• Abstract classes may contain abstract methods, which are implemented
in subclasses
• Abstract methods can only be defined inside Abstract classes

© All rights reserved.


Abstract Class Example
• Consider creating Cat class and Dog class
• Both are pets, i.e., both extends a superclass Pet
• Pet class is abstract because (sensibly) there is no actual animal
called “pet”

© All rights reserved.


Pet Class
Using the keyword Abstract implies that
the Pet class cannot be instantiated

Abstract methods to be implemented by subclasses

© All rights reserved.


Cat Class
Cat is a subclass of Pet

Calls upon the constructor of the superclass

This is the implementation of the Abstract methods

© All rights reserved.


Dog is a subclass of Pet
Dog Class

Calls upon the constructor of the superclass

This is the implementation of the Abstract methods

Exercise: Draw the UML diagram


for Pet, Cat, Dog classes

© All rights reserved.


Abstract Class Example Test

// output
meaw
play with yarn
hunting mice
bark
play fetch
barking at strangers

© All rights reserved.


Polymorphism
• Polymorphism means that a superclass can refer to a subclass
• Polymorphism can be thought of as “up-casting”

// output
meaw
play with yarn
bark
play fetch

© All rights reserved.


InstanceOf
Operator

InstanceOf operator is used to test if


an object is a member of a class

© All rights reserved.


The Object Class
• Every class in Java is implicitly a subclass of the Object class
• Therefore, every class automatically inherits all methods implemented
by the Object class
• Remember toString and equals methods! They are actually inherited
from the Object class
• What other methods exist in the Object class? Google to find out.
• Naturally, a class may override any of the methods inherited from the
Object class
• The Object class can be down-casted to any other class
• Use the keyword instanceOf to test “cast-ability” when needed`

© All rights reserved.


Example: Overriding
Methods from The Object
Class

instanceof is used to check “cast-ability”

This is called “down-casting”

© All rights reserved.


The final Keyword
• The final keyword can be used to prevent extending a class
• The final keyword can be used to prevent overriding a method

public class final A {


…. Creating subclasses of class A is not allowed
}

public class B {
public final void C {
… Subclasses of B are NOT allowed to override method C
}
}

© All rights reserved.


Interface
• Another form of inheritance in Java
• Interfaces describe generic behaviors that subclasses must follow but
always leave the implementations details to them
• Thus, an Interface can only have constants and abstract methods
• Subclasses must override methods to provide implementation
• By comparison, with normal inheritance, superclasses may provide
implementations that subclasses may use or may override

© All rights reserved.


<<Inteface>>
Interface
Flyable
Example
+fly(): void

Bird Rocket
-species: String
-color: String -name: String

+Bird(species:String, color:String) +Rocket(name:String)


+getColor(): String +getName(): String
+getSpecies(): String +fly(): void
+fly(): void

© All rights reserved.


Flyable Interface

public interface Flyable {

public void fly(); • Interfaces provide no implementation


• No need to define this method as
} abstract because that is implicitly
understood
• Do not use protected with methods
inside interfaces

© All rights reserved.


Bird Class
Use the keyword “implements” to
create a subclass of an interface

A subclass must provide implementations for


methods inherited from an Interface

Question: if Bird class was part of a big


software, do you think using a class or
enum for species and color attributes is
better than using a string?
© All rights reserved.
Rocket Class

© All rights reserved.


Flyable Test Class

Polymorphism (or up-casting) also


woks with interfaces

• The superclass was changed from Bird to Rocket


• This is called “dynamic binding”, which means
that a superclass can switch between subclasses
at will during execution

// output
Fly with wings
Fly with engine

© All rights reserved.


GeometricObject x = new Circle(3);
GeometricObject y = x.clone();
System.out.println(x == y);
}
}

13.8 Interfaces vs. Abstract Classes


Interface vs. Abstract Classes
A class can implement multiple interfaces, but it can only extend one superclass.
Key
An interface can be used more or less the same way as an abstract class, but defining Point

• A class
an interface may implement
is different from definingmore than
an abstract class.one
Tableinterface buttheit
13.2 summarizes can extends only
differences.
one superclass

TABLE 13.2 Interfaces vs. Abstract Classes


Variables Constructors Methods
Abstract class No restrictions. Constructors are invoked by subclasses through No restrictions.
constructor chaining. An abstract class cannot be
instantiated using the new operator.
Interface All variables must be No constructors. An interface cannot be instantiated All methods must be public
public static final. using the new operator. abstract instance methods

© All rights reserved.


Summary
• Inheritance is one of the major benefits of object-oriented
programming
• Inheritance allows reusing functionality and avoiding redundancy
• DRY (Don’t Repeat Yourself) is a principle in software engineering that is
emphasized by inheritance
• Superclass can be regular classes, abstract classes or interfaces
• Polymorphism allows superclasses to refer to subclasses

© All rights reserved.

You might also like