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

02 Inheritance

The document discusses object-oriented design principles like inheritance, abstract classes, and method redefinition. It provides examples of using inheritance to design class hierarchies for collections like lists and implementing a stack class using inheritance versus composition.

Uploaded by

Ablack
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

02 Inheritance

The document discusses object-oriented design principles like inheritance, abstract classes, and method redefinition. It provides examples of using inheritance to design class hierarchies for collections like lists and implementing a stack class using inheritance versus composition.

Uploaded by

Ablack
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

DESAIN DAN ANALISIS BERORIENTASI OBJEK

Kode: MWP52TI017

Inheritance
Capaian Pembelajaran
• CP-MK
• Mampu mendesain, merancang, dan menganalisis suatu permasalahan ke
dalam bentuk perangkat lunak
• CP-Pertemuan
• Understand what we mean by inheritance.
• Understand the difference between abstract and concrete classes.
• Know when to use inheritance.

Indah Permatasari 2
Outline
• Introduction
• Designing a Class Hierarchy
• Adding Implementations to a Class Hierarchy
• Abstract Classes
• Redefining Methods
• Implementing a Stack Class
• Multiple Inheritance
• Guidelines for Using Inheritance

Indah Permatasari 3
INTRODUCTION
• Inheritance allows us to specify that a class gets some of its
characteristics from a parent class and then adds unique features of
its own – this leads to the description of whole families of objects.
• Inheritance allows us to group classes into more and more general
concepts, so that we can reason about larger chunks of the world that
we live in.
• A subclass inherits all of the fields, messages, methods (and
assertions) of its superclass.

Indah Permatasari 4
What is Inheritance?

Indah Permatasari 5
DESIGNING A CLASS HIERARCHY
• Let’s look at a larger example.
• We want to model collections, objects that can hold onto other objects for
later use. After some deliberation, we decided that we need four styles of
collection:
• List: A collection that keeps all of its objects in the order in which they were inserted.
• Bag: A collection that doesn’t keep its objects in order.
• LinkedList: A collection that keeps its objects in order using an implementation of a
sequence of objects in which each object points to the next in the sequence. A linked
list can be updated easily, but access is slow because we have to walk down the list.
• ArrayList: A collection that keeps its objects in order using an array, a sequence of
adjacent memory locations. Arrays have fast access but updating is slow because we
may have to shift elements around or create a new array on each update.

Indah Permatasari 6
DESIGNING A CLASS HIERARCHY
• Collection must go at the top
• we notice that most of the collections
keep their objects in order, but Bag
doesn’t – this suggests that Bag
should be placed directly under
Collection, in a separate branch from
the other classes.
• we notice that List does not commit to
internal implementation, whereas
LinkedList and ArrayList do

Indah Permatasari 7
Placing messages in a hierarchy

Indah Permatasari 8
Advantages of inheritance
• It is an abstraction mechanism which may be used to classify entities
• It is a reuse mechanism at both the design and the programming level
• The inheritance graph is a source of organizational knowledge about
domains and systems

Indah Permatasari 9
Problems with inheritance
• Object classes are not self-contained. They cannot be understood
without reference to their super-classes
• Designers have a tendency to reuse the inheritance graph created
during analysis. Can lead to significant inefficiency
• The inheritance graphs of analysis, design and implementation have
different functions and should be separately maintained

Indah Permatasari 10
Inheritance and OOD
• There are differing views as to whether inheritance is fundamental to
OOD.
• View 1. Identifying the inheritance hierarchy or network is a fundamental part
of object-oriented design. Obviously this can only be implemented using an
OOPL.
• View 2. Inheritance is a useful implementation concept that allows reuse of
attribute and operation definitions. Identifying an inheritance hierarchy at the
design stage places unnecessary restrictions on the implementation
• Inheritance introduces complexity and this is undesirable, especially
in critical systems

Indah Permatasari 11
ADDING IMPLEMENTATIONS TO A CLASS
HIERARCHY
• the implementation elements (fields, constructors and methods)
must be added.
• we’ll look at the issue of where to put the methods, because that will
lead us on to two important concepts: abstraction and redefinition.

Indah Permatasari 12
ADDING IMPLEMENTATIONS TO A CLASS
HIERARCHY
• We conclude that it’s impossible to write a contains method on the
Collection class because the search algorithm is going to be different
for ordered and unordered collections. So we must, at least,
implement a contains method on Bag. But how about List and its
subclasses? With a little thought, using the other messages that
we’ve introduced, we can write a contains algorithm that works for
any kind of List (see Implementation Point 3).

Indah Permatasari 13
Implementation Point 3

• Writing aMessage without specifying the object that is to receive


the message means ‘send aMessage to the current object’ (some
programmers prefer to write this.aMessage() instead). For
example, elementAt(i) means ‘find the value of the ith element
of the current List object’.

Indah Permatasari 14
ADDING IMPLEMENTATIONS TO A CLASS
HIERARCHY
• An unfinished method is called an abstract method (or abstract
operation), because it’s not real, it’s not solid, you can’t kick it.
• The complement to an abstract method is a concrete method (or
concrete operation).
• A concrete method has real lines of code, it’s solid, you can kick it.
• In UML, abstract methods are shown in italics and concrete methods
are not – where italics are impractical, you can put {abstract} to the
right of the method instead.

Indah Permatasari 15
ABSTRACT CLASSES
• An abstract class is a
class with at least one
abstract method – the
abstract method may be
introduced on the class
itself, or it may be
inherited from a
superclass.
• Placing methods in a
hierarchy (fig.)

Indah Permatasari 16
Abstract class names in italics

Indah Permatasari 17
The advantages of abstract classes
• Abstract classes have the following advantages:
• They permit richer and more flexible modeling; for example, our List class
has all three messages – contains, elementAt and
numberOfElements – despite the fact that we can’t provide concrete
methods for all of them.
• They lead to more code sharing, because we can write concrete methods that
use abstract methods; for example, the contains method for List invokes
abstract methods.

Indah Permatasari 18
REDEFINING METHODS
• Object orientation allows us to redefine elements that we inherit.
• In its simplest form, redefinition allows a subclass to change the
implementation of an inherited method – the message stays the same
but the lines of code are replaced.
• Another form of redefinition allows us to make a message more
visible in a subclass: since we’ve only seen public and private
visibilities up to this point, this means that a subclass can turn a
private message into a public message.
• Yet another form of redefinition allows us to change the name or
type of an attribute.
Indah Permatasari 19
The reasons use Redefined method
• There are three good reasons why we would redefine a method:
• The inherited method was abstract and we want to make it concrete, by
giving it some code – for example, contains is abstract on Collection but we
need it to be concrete on Bag and List.
• The method needs to do some additional work in the subclass – for example,
a toString method would have to summarize any new attributes that were
introduced by the subclass.
• We can provide a better (more efficient or more accurate) implementation for
the subclass – for example, if we add an index to our LinkedList class, we can
redefine contains to be faster than the linear algorithm used by List.

Indah Permatasari 20
Redefined method to superclass
• Every object-oriented language allows a redefined method to invoke
the one on its superclass (see Implementation Point 4).

Indah Permatasari 21
IMPLEMENTING A STACK CLASS
Implementing a Stack using Inheritance
Person aPerson = new Person();
Stack aStack = new Stack();
aStack.push(new Plate("Wedgwood"));
aStack.push(new Plate("Royal Doulton"));
aStack.push(new Plate("Domestic green"));
aPerson.take(aStack.pop());

aPerson.take(aStack.firstElement());

Indah Permatasari 22
Implementing a Stack using Composition

aPerson.take(aStack.firstElement());

Indah Permatasari 23
Inheritance versus Composition
• Inheritance has some unique advantages:
• It’s natural.
• It’s elegant.
• It allows us to write generic code – for example, code written to work for Fruit
will also work for Apple and Pear.
• Inheritance suffers from the following problems:
• It’s difficult to do well.
• It’s difficult to change when you discover deficiencies in your design.
• It’s more difficult for client programmers to understand.
• The hierarchy ‘leaks’ into client code, making it more difficult to change too.

Indah Permatasari 24
Inheritance versus Composition
• Composition achieves the same end result as inheritance (concrete
classes, concrete messages and reuse of existing code).
• However, it has the following advantages:
• It’s simpler to produce.
• It’s easier to change.
• It’s easier for clients to understand.
• It doesn’t leak into client code.

Indah Permatasari 25
MULTIPLE INHERITANCE
• Rather than inheriting the attributes and services from a single parent
class, a system which supports multiple inheritance allows object
classes to inherit from several super-classes
• Can lead to semantic conflicts where attributes/services with the
same name in different super-classes have different semantics
• Makes class hierarchy reorganisation more complex

Indah Permatasari 26
Indah Permatasari 27
Disadvantages of multiple inheritance
• It introduces complexity (for the designer and the client
programmer).
• It causes name clashes.
• It causes repeated inheritance.
• It makes compilers more difficult to write.
• It makes (fast) run-time systems more difficult to write.

Indah Permatasari 28
GUIDELINES FOR USING INHERITANCE
• Don’t overdo it: Don’t think that you have to use inheritance a lot, or even at all.
Remember that there are alternatives, such as composition and the use of
attributes (for example, a Car class with a color attribute is probably better than
three classes called Car, RedCar and BlueCar).
• A class should be ‘a kind of ’ its superclass(es): Whenever you subclass X to
produce Y, ask yourself ‘Is Y a kind of X?’ For example, Orange is a kind of
Fruit and Truck is a kind of LandVehicle, so they are valid; conversely,
Potato is not a kind of Fruit and Airplane is not a kind of LandVehicle,
so these would not make good subclasses. (Some developers use the terms
subtyping to mean ‘I am following the guideline’ and subclassing to mean ‘I might
not be’.)
• A class should be an extension of its superclass(es): In a subclass, make sure that
you only add new features; don’t be tempted to break the superclass contract by
deleting, disabling or reinterpreting features.

Indah Permatasari 29
DYNAMIC AND STATIC TYPE SYSTEMS
• A type system is a simple concept: it’s a set of rules that stop us
misusing values (primitives and objects).
• Type systems, which stop us misusing values by forcing us to declare
how we intend to use a value. A static type system detects abuses at
compile time while a dynamic type system waits until run time.
• A simple example of a type system in use is declaring that a variable
will always hold a value of a particular type:
int i;
Employee fred;

Indah Permatasari 30
DYNAMIC AND STATIC TYPE SYSTEMS
• Type systems can either be static (‘done by the compiler’) or dynamic
(‘done by the run-time system’).
• Both varieties of type system ensure that values are not misused by
the programmer: a static type system spots the abuse at compile time
while a dynamic type system waits to see if the abuse actually
happens and then stops it.

Indah Permatasari 31
DYNAMIC AND STATIC TYPE SYSTEMS
• If we write the addEmployee method in Java, we are forced to declare
a type for the parameter:
public void addEmployee(Employee anEmployee) {
...
pay = anEmployee.getPayrollNumber()
...
}

Indah Permatasari 32
DYNAMIC TYPE SYSTEMS
• Dynamic typing is the better option, because:
• It makes compilation quick and simple.
• The programmer can work quickly – ideas flow easily from the programmer’s
head into the program, because they don’t have to keep stopping to think
what kind of object they must use in this context.
• The lack of a static compiler encourages thorough testing.
• Object-oriented code is continually being reused, so faults are always found
eventually.

Indah Permatasari 33
STATIC TYPE SYSTEMS
• Static typing is a good thing because:
• Compilation is still pretty quick and, anyway, programmers don’t care how
difficult it is to write a compiler.
• It can be used to improve run-time performance.
• It can be used to pick up spelling mistakes.
• It forces some documentation of the code.

Indah Permatasari 34
POLYMORPHISM
• the ability of different objects to perform the appropriate method in
response to the same message is known as polymorphism.
• the selection of the appropriate method depends on the class used to
create the object
• Polymorphism, which enables a variable to hold different types of value
and a message to be associated with more than one method. The specific
type of value or method applicable in any case is determined at run time.
• Polymorphism is derived from the Greek word stems poly, meaning many,
and morph, meaning shape.
• Therefore, polymorphic means ‘having many shapes’.
• We can apply the term separately to variables and to messages: a polymorphic
variable refers to different types of value at different times; a polymorphic message
has more than one method associated with it.

Indah Permatasari 35
Polymorphic Variables
Truck t;

Indah Permatasari 36
Truck inheritance

Indah Permatasari 37
LandVehicle variable

Indah Permatasari 38
Polymorphic Messages

Indah Permatasari 39
DYNAMIC BINDING

Indah Permatasari 40
Activity

Indah Permatasari 41
• Figure 4.7 shows our Shape hierarchy with an sh = sq;
additional class Triangle. Consider the
following code fragment: • What do you think the effect of the following
message sends would be (assuming a static
Shape sh; type system)?
Triangle tr = new Triangle(); 1. sh.getPerimeter();
Square sq = new Square(); 2. sq.getPerimeter();
• Which of the following assignments would be 3. tr.getPerimeter();
correct? (Remember to think ‘Is it a kind of?’) 4. tr.getHeight();
1. sh = tr; 5. sq.getHeight();
2. sh = sq; 6. sh.getHeight();
3. sq = tr;
4. tr = sq;
5. tr = sh;
6. sq = sh;

Indah Permatasari 42
TYPE CASTING AND EXPLICIT CASTS
• Converting a value from one type to another is called casting
(because we cast the value in a new light).
• Casting between object types: with implicit casting, the compiler can
automatically convert between types of variable; with explicit casting,
the programmer must specify that an object is to be considered as a
different type.
• Implicit casts enrich statically-typed programming languages by
allowing us to combine different types of values in expressions and by
allowing us to assign different types of values to variables.
• But we can go one step further, by allowing the programmer to use an explicit
cast, to move from one context to a compatible, but narrower, context.

Indah Permatasari 43
Terima kasih.
“Design is not just what it looks like and feels like. Design is how it works.”
– Steve Jobs

Indah Permatasari 44

You might also like