Programming Paradigms CSI2120
Review of Object-oriented Programming
• Acknowledgement
Copyright By PowCoder代写 加微信 powcoder
– These slides are a barely modified version of the slides for Chapter 2, Object-Oriented Software Engineering: Practical Software Development using UML and Java by and ̀re
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
1. What is Object Orientation?
• Procedural paradigm:
– Softwareisorganizedaroundthenotionofprocedures – Proceduralabstraction
• Worksaslongasthedataissimple – Addingdataabstractions
• Groupstogetherthepiecesofdatathatdescribesome entity
• Helpsreducethesystem’scomplexity. – Such as records and structures
• Object oriented paradigm:
– Organizingproceduralabstractionsinthecontextofdata
abstractions
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Object Oriented Paradigm
• An approach to the solution of problems in which all computations are performed in the context of objects.
– Theobjectsareinstancesofclasses,which:
• aredataabstractions
• containproceduralabstractionsthatoperateonthe objects
– Arunningprogramcanbeseenasacollectionofobjects collaborating to perform a given task
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
A View of the Two Paradigms
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
2 Classes and Objects
– Achunkofstructureddatainarunningsoftwaresystem
– Hasproperties
• Representingitsstate
– Hasbehaviour
• How it acts and reacts
• May simulate the behaviour of an object in the real world
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
• A class:
– Aunitofabstractioninanobjectoriented(OO)program
– Representssimilarobjects • Itsinstances
– Akindofsoftwaremodule
• Describesitsinstances’structure(properties)
• Containsmethodstoimplementtheirbehaviour
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Is Something a Class or an Instance?
– Somethingshouldbeaclassifitcouldhaveinstances
– Somethingshouldbeaninstanceifitisclearlyasinglemember
of the set defined by a class
– Class;instancesareindividualfilms.
• Reel of Film:
– Class;instancesarephysicalreels
• Film reel with serial number SW19876
– InstanceofReelOfFilm
• Science Fiction
– InstanceoftheclassGenre.
• Science Fiction Film
– Class; instances include ‘Star Wars’
• Showing of ‘Star Wars’ in the at 7 p.m.:
– InstanceofShowingOfFilm
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Common Approach to Naming Classes
– Usecapitalletters
• E.g.BankAccountnotbankAccount
– Usesingularnouns
– Usetherightlevelofgenerality • E.g.Municipality,notCity
– Makesurethenamehasonlyonemeaning • E.g.‘bus’hasseveralmeanings
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
: What is so great about classes?
• “Classes are there to help you organize your code and to reason about your programs”.
• “A class is the representation of an idea, a concept, in the code. An object of a class represents a particular example of the idea in the code”.
– “Without classes, a reader of the code would have to guess about the relationships among data items and functions – classes make such relationships explicit and “understood” by compilers. With classes, more of the high-level structure of your program is reflected in the code, not just in the comments”. [emphasis added]
Source: http://www.stroustrup.com/bs_faq.html#class, accesed Jan. 2019
CSI2120 Programming Paradigms
3 Instance Variables
• Variables defined inside a class corresponding to data present in each instance
– Alsocalledfieldsormembervariables – Attributes
• Simpledata
• E.g.name,dateOfBirth – Associations
• Relationshipstootherimportantclasses • E.g.supervisor,coursesTaken
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Variables vs. Objects
• A variable
– Referstoanobject
– Mayrefertodifferentobjectsatdifferentpointsintime
• An object can be referred to by several different variables at the same time
• Type of a variable
– Determineswhatclassesofobjectsitmaycontain
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Class variables
• A class variable’s value is shared by all instances of a class.
– Alsocalledastaticvariable
– Ifoneinstancesetsthevalueofaclassvariable,thenallthe other instances see the same changed value.
– Classvariablesareusefulfor:
• Defaultor‘constant’values(e.g.PI)
• Lookuptablesandsimilarstructures – Caution:donotover-useclassvariables
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
4 Methods, Operations and Polymorphism
• Operation
– Ahigher-levelproceduralabstractionthatspecifiesatypeof
– Independentofanycodewhichimplementsthatbehaviour
• E.g.calculatingarea(ingeneral)
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Methods, Operations and Polymorphism
– Aproceduralabstractionusedtoimplementthebehaviourof
– Severaldifferentclassescanhavemethodswiththesame name
• Theyimplementthesameabstractoperationinways suitable to each class
• E.g.calculatingareainarectangleisdonedifferently from in a circle
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Polymorphism
• A property of object oriented software by which an abstract operation may be performed in different ways in different classes.
– Requiresthattherebemultiplemethodsofthesamename
– Thechoiceofwhichonetoexecutedependsontheobject that is in a variable
– Reducestheneedforprogrammerstocodemanyif-elseor switch statements
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
5 Organizing Classes into Inheritance Hierarchies
• Superclasses
– Containfeaturescommontoasetofsubclasses
• Inheritance hierarchies
– Showtherelationshipsamongsuperclassesandsubclasses – AtriangleshowsageneralizationinUML
• Inheritance
– Theimplicitpossessionbyallsubclassesoffeaturesdefined
in its superclasses
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
An Example Inheritance Hierarchy
• Inheritance
– Theimplicitpossessionbyallsubclassesoffeaturesdefined
in its superclasses
See in Umple
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
The Isa Rule
• Always check generalizations to ensure they obey the isa rule
– “Acheckingaccountisanaccount”
– “Avillageisamunicipality”
• Should ‘Province’ be a subclass of ‘Country’?
– No,itviolatestheisarule
• “Aprovinceisacountry”isinvalid!
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
A Possible Inheritance Hierarchy of Mathematical Objects
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Make Sure all Inherited Features Make Sense in Subclasses
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
6 Inheritance, Polymorphism and Variables
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Some Operations in the Shape Example
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Abstract Classes and Methods
• An operation should be declared to exist at the highest class in the hierarchy where it makes sense
– Theoperationmaybeabstract(lackingimplementation)at that level
– Ifso,theclassalsomustbeabstract
• Noinstancescanbecreated
• Theoppositeofanabstractclassisaconcreteclass
– Ifasuperclasshasanabstractoperationthenitssubclasses at some level must have a concrete method for the operation
• Leafclassesmusthaveorinheritconcretemethodsfor all operations
• Leafclassesmustbeconcrete
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Overriding
• A method would be inherited, but a subclass contains a new version instead
– Forrestriction
• E.g.scale(x,y)wouldnotworkinCircle
– Forextension
• E.g.SavingsAccountmightchargeanextrafeefollowing every debit
– Foroptimization
• E.g.ThegetPerimeterLengthmethodinCircleismuch simpler than the one in Ellipse
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Methods and Inheritance
• How a decision is made about which method to run
1. If there is a concrete method for the operation in the current
class, run that method.
2. Otherwise, check in the immediate superclass to see if there is a method there; if so, run it.
3. Repeat step 2, looking in successively higher superclasses until a concrete method is found and run.
4. If no method is found, then there is an error
• InJavaandC++theprogramwouldnothavecompiled
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Dynamic Binding
• Occurs when decision about which method to run can only be made at run time
– Neededwhen:
• Avariableisdeclaredtohaveasuperclassasitstype, and
• There is more than one possible polymorphic method that could be run among the type of the variable and its subclasses
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
7 Concepts that Define Object Orientation
• The following are necessary for a system or language to be OO
– Identity
• Eachobjectisdistinctfromeachotherobject,andcanbe
referred to
• Two objects are distinct even if they have the same data
• The code is organized using classes, each of which describes a set of objects
– Inheritance
• The mechanism where features in a hierarchy inherit from
superclasses to subclasses – Polymorphism
• The mechanism by which several methods can have the same name and implement the same abstract operation.
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Other Key Concepts
• Abstraction
– Object->somethingintheworld
– Class->objects
– Superclass->subclasses
– Operation->methods
– Attributesandassociations->instancevariables
• Modularity
– Codecanbeconstructedentirelyofclasses
• Encapsulation
– Detailscanbehiddeninclasses
– Thisgivesrisetoinformationhiding:
• Programmers do not need to know all the details of a class © Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
: What is “OOP” and what’s so great about it?
• “Object-oriented programming is a style of programming originating with Simula (…) relying of encapsulation, inheritance, and polymorphism.”
• “It means programming using class hierarchies and virtual functions to allow manipulation of objects of a variety of types through well-defined interfaces and to allow a program to be extended incrementally through derivation.”
Source: http://www.stroustrup.com/bs_faq.html#class, accesed Jan. 2019
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
The Origins of Java
– The first object oriented programming language was Simula-67
• designed to allow programmers to write simulation
programs • 1980s
– SmalltalkwasdevelopedatXeroxPARC
• New syntax, large open-source library of reusable code,
bytecode, platform independence, garbage collection. – C++wasdevelopedbyB.StroustrupatATTLabs
• Startedin1979.Theinitialversionwascalled”Cwith
Classes”. • 1990s
– SunMicrosystemsstartedaprojecttodesignalanguagethat could be used in consumer ‘smart devices’: Oak
• When the Internet gained popularity, Sun seized the opportunity and renamed the new language Java. It was first presented at the SunWorld ’95 conference.
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
• Review of Java in a Few Slides
CSI2120 Programming Paradigms
Java documentation
• Looking up classes and methods is an essential skill
– Lookingupunknownclassesandmethodswillgetyoua
long way towards understanding code
• Java documentation can be automatically generated by a
program called Javadoc
– Documentationisgeneratedfromthecodeandits comments
– Youshouldformatyourcommentsasshowninsomeofthe book’s examples
• Thesemayincludeembededhtml
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Characters and Strings
• Character is a class representing Unicode characters – Morethanabyteeach
– Representanyworldlanguage
• char is a primitive data type containing a Unicode character
• String is a class containing collections of characters
– +istheoperatorusedtoconcatenatestrings
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Arrays and Collections
• Native arrays are of fixed size and lack methods to manipulate them
• ArrayList is part of the collection framework and is a growable array to hold a collection of other objects
• Iterators can be used to access members ArrayList
while(i.hasNext())
System.out.println(i.next());
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
• Java is very strict about types
– IfvariablevisdeclaredtohavetypeX,youcanonlyinvoke
operations on v that are defined in X or its superclasses
• Even though an instance of a subclass of X may be actually stored in the variable
– If you know an instance of a subclass is stored, then you can cast the variable to the subclass
E.g. if I know a Vector contains instances of String, I can get the next element of its Iterator using: (String)i.next();
To avoid casting you should use generics as in the previous slide:
ArrayList
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Exceptions
• Anything that can go wrong should result in the raising of an Exception in Java
– Exceptionisaclasswithmanysubclassesforspecificthings that can go wrong
• Use a try – catch block to trap an exception try
{ // some code
}catch (ArithmeticException e)
{ // code to handle division by zero
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Interfaces
Like abstract classes, but cannot have executable statements
– Defineasetofoperationsthatmakesenseinseveral classes
– AbstractDataTypes
A class can implement any number of interfaces
– Itmusthaveconcretemethodsfortheoperations
You can declare the type of a variable to be an interface
– Thisisjustlikedeclaringthetypetobeanabstractclass
Important interfaces in Java’s library include
– Runnable,Collection,Iterator,Comparable,Cloneable © Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Packages and importing
• A package combines related classes into subsystems – Alltheclassesinaparticulardirectory
• Classes in different packages can have the same name – Althoughnotrecommended
• Importing a package is done as follows: – importfinance.banking.accounts.*;
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Access control
• Applies to methods and variables – public
• Anyclasscanaccess – protected
• Onlycodeinthepackage,orsubclassescanaccess – nomodifier(blank)
• Onlycodeinthepackagecanaccessbutnotsub- classes outside package
• Onlycodewrittenintheclasscanaccess • Inheritancestilloccurs!
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Threads and concurrency
– Sequenceofexecutingstatementsthatcanberunning
concurrently with other threads • To create a thread in Java:
1. Create a class implementing Runnable or create a class extending Thread
2. Implement the run method as a loop that does something for a period of time
3. Create an instance of this class
4. Invoke the start operation, which calls run
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Programming Style Guidelines
• Remember that programs are for people to read – Alwayschoosethesimpleralternative
– Rejectclevercodethatishardtounderstand
• Stroustrup:“Don’tbeclever”.
– Shortercodeisnotnecessarilybetter
• Choose good names
– Makethemhighlydescriptive
– Lethbridge/Laganière: “Do not worry about using long names”
– Stroustrup: “Don’t use overly long names; they are hard to type, make lines so long that they don’t fit on a screen, and are hard to read quickly.”
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Programming style …
• Comment extensively
– Commentwhateverisnon-obvious
– Donotcommenttheobvious
– Commentsshouldbe25-50%ofthecode
– Stroustrup:“Ifthecommentandcodedisagree,bothare probably wrong”.
• Organize class elements consistently
– Variables,constructors,publicmethodsthenprivate
• Be consistent regarding layout of code
– Stroustrup:“Suchstyleissuesareamatterofpersonaltaste. Often, opinions about code layout are strongly held, but probably consistency matters more than any particular style”
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Programming style …
• Avoid duplication of code – Donot‘clone’ifpossible
• Createanewmethodandcallit
• Cloningresultsintwocopiesthatmaybothhavebugs
– When one copy of the bug is fixed, the other may be forgotten
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
Programming style …
• Adhere to good object oriented principles – E.g.the‘isarule’
• Prefer private as opposed to public
• Do not mix user interface code with non-user interface code – Interactwiththeuserinseparateclasses
• Thismakesnon-UIclassesmorereusable
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
10 Difficulties and Risks in Object- Oriented Programming
• Language evolution and deprecated features:
– Javaisevolving,sosomefeaturesare‘deprecated’atevery
– Butthesamethingistrueofmostotherlanguages
• Efficiency can be a concern in some object oriented systems – Javacanbelessefficientthanotherlanguages
• VM-based
• Dynamicbinding
• Stroustrup [HOPL-III, 2007]
– “AnotherproblemwasthatJavaencouragedalimited“pure object-oriented” view of programming with a heavy emphasis on run-time resolution and a de-emphasis of the static type system”
© Lethbridge/Laganière 2005 Chapter 2: Review of Object Orientation
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com