object-oriented programming conceptsjarakaki/lp3/oop.pdf · object-oriented programming concepts...
TRANSCRIPT
Object-Oriented ProgrammingConcepts
Four important concepts make up theObject-Oriented Programming para-digm:
1. Object-oriented programs are madeup from collections ofObjects.
2. These objects communicate with oneanother in order to perform the pro-gram’s tasks. This communication isby way of Messages.
3. Objects are defined by templates(type-specifiers) calledClasses.
4. Classes canInherit part of theirbehaviour from “ancestor” classes(SuperClasses).
Objects
The real world is made up of objects:students, aeroplanes, rocks, lecturers,etc.
These all have “state” and they all have“behaviour.”
A Software Objectis a transference ofthis idea to programming:
A Methodis simply a function or proce-dure that belongs to a software object.(The termmethodis very common in OOP.)
A Software Object(or simplyObject) isa software bundle of variables (the state)and relatedmethods(the behaviour).
The user of the object can only access itvia its publicApplication ProgrammingInterface(API). The public methods(and sometimes variables) of the APIare allowed to change the internal stateof the object.
The usercannotchange the internalstate of the object directly.
“Data Hiding”/“Encapsulation” .
PublicAPI
PrivateImplementationDetails
privatemethods
and variables
A “ Counter” object. Models a digital up/downcounter.
• 2 hidden pieces of state:“currentCount”, “ countDir”.
• 3 publicly accessible methods makingup the API: “setCountDirection”,“clearCounter”, “ applyClock”.
currentCountcountDir
setCountDirection
applyClock
clearCo
unter
Once the API is defined, you have freedom tochange the internal implementation at any time.The API is the “contract” between the objectdesigner and the object user.
A “ BankBalance” object. Models a bank bal-ance.
• 1 hidden piece of state:“currentBalance”, the amount in theaccount.
• 1 hidden method: “calcInterest” .
• 2 publicly accessible methods makingup the API: “depositCash”,“withdrawCash”.
The user can only modify the balance via thetwo publicly accessible methods. These willhave checks to prevent withdrawals from anempty account, etc.
currentBalance
depositC
ashwith
draw
Cas
hcalcInterest
The Benefits of Objects
Encapsulating related variables andmethods into a neat software bundle is asimple yet powerful idea with two majorbenefits:
1. Modularity : The source code for anobject can be written and maintainedindependently from the source codefor other objects. Also, an object canbe easily passed around the system.
2. Information Hiding : An object hasa public interface (API) that otherobjects can use to communicate withit. However, the object can maintainprivate information and methods thatcan be changed at any time withoutaffecting the other objects thatdepend on it.
Messages
Software objects interact and communi-cate by sendingmessagesto each other.If object A wants objectB to performone of its methods, it sends a message toB requesting that behaviour.
Sometimes the receiving object needsmore information so that it knowsexactly what to do.
Object B
Object A
Message
This information is passed along withthe message as aparameterto a method.
A message is made up from three parts:
1. The name of the object to which themessage is addressed,(My “ BankBalance” Object),
2. The name of the method to perform,(depositCash),
3. Any parameters needed,(e.g.,400).
My “ BankBalance” Object
Object A
Message:depositCash(400)
Classes
A program usually needs many objectsof the same sort. A banking programmay have manyBankBalance objectswhich represent different customers, butwhich all share the same pattern ofmethods and variables.
We say that each uniqueBankBalanceobject is anInstanceof theClassofBankBalance objects.
Every such object is independent ofevery other, but they all share the samelayout.
We capture the commonality by defin-ing ablueprintor templatefor allobjects of the same sort. This blueprintis aClass Definition.
Note that a class is not itself an object(usually!). In order to make a new user-defined object you must perform twosteps:
1. Write a class definition for theobject, setting out its variables andmethods,
2. Instantiatethe class to create anobject (which is aninstanceof theclass). You may instantiate a class asoften as you like to create newobjects of the same type.
A Classis a blueprint, (template, proto-type), that defines the methods and vari-ables common to all objects of a certainkind
Every new instance of the class will getits own set ofinstance variables.
All objects instantiated from the sameclass will share theinstance methodsofthe class.
Classes may also defineClass VariablesandClass Methods.
1. A Class Variableis one which issharedamongstall instances of theclass.
A class variable may be used, for example,to represent the standard output stream ofan application. Since a program has only asingle standard output stream, this is a gooduse for such a variable.
In the “Hello World” application “out” is aclass variable representing the standardoutput stream. It belongs to class “System”and has method “println” (inter alia).
2. A Class Methodis one which may becalledeven if no instance of its classhas been created.
The “main” method in the “Hello World”application is an example of a classmethod. No instance of the class“HelloWorld” is created by this application.
public class HelloWorld {public static void main (String args[]) {
System.out .println("Hello World");}
}
HelloWorld.java
class method “main” of
class variable “out” of
class “HelloWorld”
class “System”
Class Diagrams
1. “Doughnut Diagrams,”
2. Object Modeling Technique (OMT)diagrams,
3. Unified Modeling Language (UML)diagrams.
current-
depositC
ashwith
draw
Ca
sh
calcInterest
Balance
Note: noshading, henceclassdiagram
BankBalancepublic withdrawCash(amount)public depositCash(amount)private calcInterest()private currentBalance
BankBalance
+withdrawCash(amount : integer)+depositCash(amount : integer)−calcInterest()
−currentBalance : integer
Inheritance
In Object-Oriented Programming(OOP), classes may be defined in termsof other classes. They mayInherit theattributes of other classes and specialisethem as needed.
“Matrix” Class
“RotationMatrix”Class
“TranslationMatrix”Class
“ScalingMatrix”Class
Superclass
Subclasses
ClassHierarchyDiagram
Each subclassinheritsstate (in the formof variable declarations) from its super-class. HenceRotationMatrices, Transla-tionMatrices andScalingMatrices all geta copy of the variables of classMatrix.
Each subclass also inherits all themeth-odsof its superclass. Hence, any meth-ods defined forMatrix areautomaticallyavailable to all its subclasses.
Subclasses get the variables and meth-ods of their superclass “for free”. How-ever, they canspecialisetheir behaviourby adding new methods and/or varia-bles.
They can alsooverrideinherited meth-ods and provide specialised behaviourfor these methods. The subclass imple-mentation replaces the superclass imple-mentation with the same name.
The Benefits of Inheritance
1. Subclasses provide specialisedbehaviours from the basis of com-mon elements provided by the super-class.
Using inheritance, programmerscan reuse the code in the superclassmany times.
2. Programmers can implement super-classes calledAbstract Classes. Anabstract class defines “genericbehaviours.”
An abstract superclass defines, andmay partially implement, the behav-iour, but much of the class is unde-fined and unimplemented. Otherprogrammers fill in the details withspecialised subclasses.