Starting Out With Programming Logic & Design - Chapter14 - Object Oriented Programming
Starting Out With Programming Logic & Design - Chapter14 - Object Oriented Programming
Object-Oriented Programming
Second Edition
by Tony Gaddis
Chapter Topics
14.1 Procedural and Object-Oriented
Programming
14.2 Classes
14.3 Using the Unified Modeling Language to
Design Classes
14.4 Inheritance
14.5 Polymorphism
14-2
14-3
14-4
14.2 Classes
A class is code that specifies the fields and
methods for a particular type of object
A class is coded and contains methods and fields
Think of it like a blueprint, such as a blueprint for a
house
Its a detailed description
14-5
14.2 Classes
Creating a class
Class ClassName
Field declarations and method declarations
End Class
14-6
14.2 Classes
Access specifiers
Private allows class members to be hidden from
code outside the class
Public allows for all parts of the code to access the
class members
It is common practice to make all fields private and
to provide access only to those field through
methods
Therefore, the methods should be public
14-7
14.2 Classes
Continued
Copyright 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
14-8
14.2 Classes
14-9
14.2 Classes
Inside Class Listing 14-3
The field are defined as private to ensure data
hiding
The methods are public so they can be accessed by
main
When the set modules are called, a String is passed
into the method as an argument and that value is
set to the private field
When the get modules are called, they simply
return the value of the private field
14-10
14.2 Classes
14-11
14.2 Classes
14-12
14.2 Classes
Inside Program 14-1
An variable is created myPhone
myPhone is then used with the keyword New to
create the object in memory
Values are then stored in the objects field by
calling the class methods
Call myPhone.setManufacturer(Motorola)
14-13
14.2 Classes
Constructor is a method that is automatically
called when an object is created
The purpose is to initialize an objects fields with
starting values
A programmer can write their own constructor to
initialize fields
Or they can use the default constructor that is
available with most programming languages
14-14
14-15
14-16
14-17
14.4 Inheritance
Inheritance allows a new class to extend an
existing class, whereas the new class inherits
the members of the class it extends
The superclass is the base class
The subclass(es) is the derived class
Figure 14-17 Bumblebees and
grasshoppers are specialized versions
of an insect
14-18
14.5 Polymorphism
Polymorphism allows you to create methods
with the same name in different classes (that
are related through inheritance
The programmer has the ability to call the correct
method depending on the type of object that is
used to call it
Polymorphism refers to an objects ability to take
different forms
14-19