Introduction to Object-Oriented-Programming course · Object-Oriented Concepts revisited (today's...
Transcript of Introduction to Object-Oriented-Programming course · Object-Oriented Concepts revisited (today's...
Slide 1
School of Compupter Science & Engineering
Introduction to Object-Oriented-Programmingcourse 67125
Slide 2
Course OverviewCourse Goals:
(1) Learn advanced Object Oriented Concepts using Java.
(2) Learn basic Object-Oriented Design.
(3) Implement various data structures using Java.
(4) Get to know various important and useful Java classes from the Java API
(5) Learn new Java 5.0 features
Slide 3
Course TopicsObject-Oriented Concepts revisited (today's lesson)
Progrmming in an Integrated Develpoment Environment (IDE)
Input-Output using streams.
Advanced Object-Oriented Concepts.
Basic Design-Patterns in OOP: Iterator, Composite.
A short introduction to UML (Unified Modelling language)
Slide 4
Course Topics (cont.)Event-Based programming and simulation.
Genericity.
The Java Collections API.
Graphical User Interface and Event-Handling in Java.
Implementing data structures in Java.
Learning new Java 5.0 concepts and features.
Slide 5
Course MechanicsCourse website: www.cs.huji.ac.il/~oop
Course Staff:
Lecturer:Tomer Hertz
Teaching Assistants: Tal El-Hay, Elad Dinur
Course “Tzar”: Moran Yassour
Course Duties:
5 programming Exercises
Final Exam
Many more details in the OOP_Mechanics.pdf file
Slide 6
Object-Oriented RevisitedObject: A thing presented to or capable of being presented to the senses.
Object-Oriented: Directed toward just about anything you can think of.
Many other different definitions. No clear agreement on what the concept actually means.
Slide 7
OOP conceptsA list of 12 OOP Guru's were locked in a single room. Each one made a list of indespensible OOP propeties. They now had 2 options:
(1) Create one long list which is the union of their individual list.
(2) Create a short list which is the intersection of their lists.
The Guru's chose the 2nd option and got a very short list indeed: it was the word “Encapsulation”!
Finally someone suggested to choose the most popular properties in all lists! This yielded 9 OOP concepts.
Slide 8
OOP concepts9 Object Oriented Concepts:
(1) Encapsulation
(2) Information/Implementation hiding
(3) State retention
(4) Object identity
(5) Messages
(6) Classes
(7) Inheritance
(8) Polymorphism
(9) Genericity
Slide 9
OOP concepts – Karel RevisitedIn order to understand these concepts let us return to Karel the Robot.
The task:We would like to create a program which allows Karel to walk through a path from start to end assuming a single path exists between the two.
Slide 10
The Karel And KarelWorld ClassesFortunately we already have both a Karel class and a KarelWorld class at our disposal.
Karel's API: public boolean setStartLocation(Point location)
public void turnLeft(), public void turnRight()
public void moveForward()
public Point getLocation()
public boolean frontIsClear()
Slide 11
The KarelWorld ClassesKarelWorld's API: public KarelWorld()
public Point getStartPosition()
public Point getEndPosition()
public void display()
Slide 12
A solutionKarelWorld world = new KarelWorld();
Karel robot = new Karel();
Point startPoint = world.getStartPosition();
boolean setOk = robot.setStartLocation(startPoint);
while(!robot.frontIsClear())
robot.turnLeft();
while(! robot.getLocation().equals(world.getEndposition) ){
while(!robot.frontIsClear())
robot.turnLeft();
robot.moverForward();
world.display();
}
Slide 13
EncapsulationEncapsulation – is the grouping of related ideas into one
unit, which can thenforth be referred to by a single name.
● An old concept dating back to the early 1940's● The basic idea – a repeating pattern could be grouped together at a “corner” of a program and invoked by a single name from several different points in the main program – a subroutine/procedure/function - encapsulation of instructions.● Advantages:
● saves computer memory (very important back then!)● saves human memory – represents a conceptual chunk that can
be considered and manipulated as a single idea.
Slide 14
OOP EncapsulationOOP Encapsulation – is the grouping of procedures
around data. (more precisely – encapsulation of a state within the procedural mechanisms for accessing and modifying that state.)An object consists of a set of methods and a set of variables:
dirlocation
turnLeft()
moveForward()frontIsClear()
getLocation()
Slide 15
OOP Encapsulation (cont.)Variables are used internally to remember information.
Variables are accessed and updated by an object's methods.
Variables are private to the object and cannot be directly accessed.
The methods form a protective ring around the central core of the variables.
dirlocation
turnLeft()
moveForward()frontIsClear()
getLocation()
Slide 16
Information/Implemention HidingInformation/Implementaion Hiding – is the use of
encapsulation to restrict from external visibility certain information or implementation decisions that are internal to the encapsulation structure.
information hiding – information from within the unit cannot be preceived outside the unit.
implementation hiding – implementation details within the unit cannot be preceived from the outside.
Many times the object allows access to information via public methods, but still hides implementation details.
Slide 17
Information/Implemention HidingKarel's direction is an example of both information hiding and of implementation hiding: We don't know whether Karel's direction is stored as a char ('e','n','s' or 'w') or as a numerical angle (with values of 0-359 deg). Note: This is true even if we have implemented a getDirection method. (why?)
The object may be seen as a “black box” to an extent observer.
The “extent observer” has full knowledge of what the object can do, but has no knowledge about how the object does what it does, and how it is constructed internally.
dirlocation
turnLeft()moveForward()frontIsClear()
getLocation()
Slide 18
Information/Implemention HidingInformation/Implementation hiding has 2 major benefits:
(1) It localizes decisions – private decisions (those within an object) have little or no impact on the rest of the system. Therefore they can be easily made and changed. (limits the “ripple of change” effect).
(2)It decouples the content of information from its form of representation. Thus, an external user of the information content. This prevents external users from “meddling” with the object's interior. Also prevents introducing connections to an object that depend on tricks or accidents of format and are therefore unstable.
Slide 19
State RetentionAn object should have the ability to retain it's state.
Traditional procedural modules (e.g. Functions) which die when they return to their caller leaving behind only their result (or return value).
Modules have no memory - when the module is called again, its as if it is reborn.
An object such as robot, is aware of its past. It retains information inside itself for an indefinite amount of time.
Slide 20
State RetentionObject's State: the values that the object holds.
For example: Karel's state includes its current location in the world, and the direction in which it is currently facing.
The way in which the object chooses to retain its state is its own internal business.
Slide 21
Partial RecapSo far we have discussed:
(1)Encapsulation
(2)Information/Implemenation hiding
(3)State retention
All three are at the core of Object Orientation.
However, they are not new ideas and have been studied for years in the field of Abstract Data Types (ADT's).
As we'll now see – Object Orientation goes well beyond the ADT.
Slide 22
Object IdentityObject identity – is the property by which each object
(regardless of its class or current state) can be identified and treated as a distinct software entity.Each object has something unique which distinguishes it from all its fellow objects.
This “something unique” is provided by the object-handle mechanism.
What is an object handle? Consider the following line of code:Karel robot = new Karel();
The right hand side of this line creates a new object (of class Karel).
Slide 23
Object Identity (cont.)Karel robot = new Karel();
An object handle is an identifier attached to an object when it is created. (AKA Object Identifier (OID)).
The object has the same handle for its entire life, regardless of its state during that time.
No two objects can have the same handle. Whenever a new object is created at run-time, the system assigns a different handle from all other past, present or future handles.
dirlocation
turnLeft()
moveForward()frontIsClear()
getLocation()
102237
Object Handle
Slide 24
Object Identity (cont.)Karel robot = new Karel();
The left-hand side of the line of code is a declaration of a variable by which the programmer can use to refer to a word of memory which can hold a value.
The assignment operation can be read as “now refers to” (or “now points to”) causes the variable robot to hold the handle of the object created on the right-hand side of the assignment statement.
No one (programmer,user,anyone) will ever actually see the handle (102237) of the new object. Instead, the programmer will access the object via the variable robot
Slide 25
Object Identity (cont.)Karel robot = new Karel();
In java this handle is a virtual address (and not a physical address).
If we create another object it will have a new and different identity.
If we now write robot1 = robot; we now have aliasing, but still each of the object's has its own unique ID.
dirlocation
turnLeft()
moveForward()frontIsClear()
getLocation()
102237102237robot
Slide 26
MessagesA Message – is the way in which a sender object ob1
conveys to a target object ob2 a demand for object ob2 to apply one of its methods.Message structure – a message is comprised of several syntactic parts, each of which is important for OOD.
In order for object ob1 to send a message to object ob2, object ob1 must know three things:
(1) The handle of ob2 – usually kept as one of ob1's variables.
(2)The name of the method of ob2 that it wishes to execute.
(3)Any additinal information (arguments) that ob2 will require in the execution of its method.
Slide 27
Messages (Cont.)The karel program provides several examples of messages e.g. robot.turnLeft();
Here robot points to (contains the handle of) the target object of the message. turnLeft() is the name of the method (of the target object) that's to be executed.
Sending of a message therefore looks like traditional calling of a function or procedure. In a procedural language we might have written:
turnLeft(Karel robot);
Notice the inversion!
Slide 28
Messages (Cont.)In the procedural approach, we appeal to a procedural unit and supply it with the object upon which to act.
In object orientation, we appeal to the object, which then executes one of its procedural units.
While this seems only a syntactic (and maybe also philosophical) difference, when polymorphism, overloading and dynamic binding are introduced, we'll see that this inversion creates and important practical difference between the two approaches. This is because different classes of objects may use the same method name for methods that accomplish different or class-specific behaviours.
Slide 29
Messages (cont.)Message arguments – each message can pass arguments back and forth (input arguments and a return value). These are sometime called the method's signature (types of arguments?)
A message therefore consists of 2 parts: the method name and its signature.
An object can be a sender and a target in different contexts.
Slide 30
Message TypesThree types of messages:
(1) Informative message – A message to an object that provides it with information to update itself. (aka update,forward, or push message). A “past-oriented” message.
(2) Interrogative message – A message to an object requesting it to reveal some information about itself (aka read,backward or pull message). A “present-oriented” message.
(3) Imperative message – A message to an object that requires the object to take some action on itself, another object, or even the envirornment around the system (aka force or action message). A “future-oriented” message.
Slide 31
Message TypesExamples:
Informative message: robot.setStartLocation(Point p); tells the Karel object where in the world it has been placed. In general tells the object about something that's happened.
Interrogative message: robot.getLocation(); which asks the robot to tell us which square it's currently on. This type of message does not change anything, it usually queries the piece of the world that the object represents.
Imperative message: robot.moveForward(); which causes the robot to move forward. This kind of message often results in the target object excuting some significant algorithm in order to work out what to do. (e.g. robot. MoveToWall() )
Slide 32
ClassesA Class – is the stencil from which objects are created
(instantiated). Each object has the same structure and behavior as the class from which it is instantiated.Whenever we execute the new command we instantiate an object that is structurally identical to all other objects created from the same class.
“Structurally identical” - all objects from the same class have the same methods and variables, as defined by their class.
Objects from the same class differ from one another in 2 ways:
(1) Each object has a different object handle.
(2)At a particular time, each object will probably have a different state. (i.e. different “values” stored in its variables).
Slide 33
Class vs. Object?The distinction between a class and an object:
A class is what you design and program
Objects are what you create (from a class) at runtime.
Therefore Object-Oriented Programming should have been called class-structured programming !
Example: Excel (see open office's Calc) is the class from which spreadsheets are created. Each spreadsheet has all the “spreadsheet machinery” available to is as an instance of the Excel class.
One may have many objects from the same class.
Slide 34
Objects in MemorySuppose we instantiate 3 different objects from the same class. All of them have the same structure (identical variables and methods).
In principle each object (instance) of a class has its own copy of the set of methods and variables it needs.
However, while (most) variables are indeed object specific, the methods need not be allocated again for each new object from the same class. Therefore all objects share the same physical copy of the methods (to save memory).
Slide 35
Object methods and variablesRecall that an object can have two types of methods variables:
Instance methods/variables – which belong to individual objects.
Class methods/variables (static) which belong to the class. By definition there is always one copy of these regardless of the number of objects which have been instantiated. Example : the constructor method.
Slide 36
InheritanceInheritance (by B from A) is the facility by which objects
of a class B may use a method or variable that would otherwise be available only to objects of class A, as if the method or variable has been defined upon B.
A is termed a superclass of B. B is a subclass of A.Allows to build software incrementally : First build classes to cope with the most straightforward (or general) case. Then, in order to deal with special cases, add more specialized classes and inherit from the first class. The new classes will be entitled to use all the methods and variables (both class and instance) of the original class.
Slide 37
Inheritance (cont.)
Aircraft ac = new Aircraft();
Glider gl = new Glider();
boolean turnOk = ac.turn(200);
gl.releaseTowline();
gl.turn(180);
ac.releaseTowline();
Aircraftbool:turn(course:int)
GliderReleaseTowline()isAttached:bool
Slide 38
Object vs. InstanceWe saw the distinction between class and object.
There is also a subtle distinction between object and instance – inheritance in a sense permits a single object to be simultaneously an instance of more than one class.
This corresponds to the real world: if you own a glider (object) it is at the same time an example of a glider and an example of an aircraft.
This demonstrates the “is a” test for inheritance: If you can say “a D is a C” then D almost certainly should be a subclass of C.
Slide 39
PolymorphismComes from two Greek words that mean “many” and “form”.
Something polymorphic has the ability to take on many forms.
Two different definitions in the literature:(A) Polymorphism – is the facility by which a single
method name may be defined upon more than one class, and may take on different implementations in each of those classes.
(B) Polymorphism – is the property whereby a variable may point to (hold the handle of) objects of different classes at different times.
Slide 40
PolymorphismExample: Shapes hierarchy
Polygonint:area()
Rectangleint:area()
Hexagon...
Triangleint: area()
Slide 41
Polymorphism (cont.)The method area() in Polygon would need a fairly sophisticated algorithm in order to compute the area of a general polygon.
All of the shapes that inherit from Polygon, inherit the method area().
However, the designer/programmer of area() for rectangle would write the code for this method very differently (and also much simpler and efficient).
Slide 42
PolymorphismIf we have a ref td to type twoDShapes which sends a message to its object as follows: td.area(); then
(a) We may not know which algorithm for computing area() will be executed.
(b) This Reason is that we many not know exactly to which class td belongs. There are 5 possiblities: Triangle, Rectangle, Hexagon, Polygon, Customer
Which causes what to happen?
Easy to construct simple code in which the class of an object cannot be determined at compile time (how?)
Slide 43
PolymorphismWhere are the 2 definitions of polymorphism here?
(1) The method area() being defined on several classes is a good example of polymorphism using definition (A).
(2) The variable td, capable of pointing to object of several different classes (for example, Triangle and Hexagon) is an example of polymorphism under definition (B).
This shows that these two aspects of polymorphism work together.
Slide 44
Polymorphism and Dynamic BindingAn Object-Oriented environment implements polymorphism is through dynamic binding. The environment inspects the actual class of the target object of a message at the last possible moment – at run-time, when the message is sent.
Dynamic Binding – (or runtime/late binding) is the technique by which the exact piece of code to be executed is assessed only at run-time (as opposed to compile-time).
Slide 45
Overriding and Overloading
The method area() originally defined by Polygon is overriden in Triangle. Triangle's method has the same name but a different algorithm.
Sometimes overriding can be used to cancel a method by redefining it simply to return an error.
Overriding – is the definition of a method defined on class C in one of C's subclasses.
Slide 46
Overriding and Overloading
Both polymorphism and overloading often require that the specific method to be executed be picked at run-time. (why?)
The distinction between polymorphism and overloading is that polymorphism allows the same method name to be defined differently across different classes, while overloading allows the same method name to be defined differently several times in the same class.
Overloading – a name or a symbol occurs when several methods (or operators) defined on the same class have that name or symbol. We say that the name or symbol is overloaded.
Slide 47
Genericity
An informative example – Designing a Linked-List:
Suppose that you are required to implement a Linked-List of integers for a specific exercise, and then required to implement a Linked-List of shapes for another exercise. What are your design options?
Genericity – is the construction of class C so that one or more of the classes that it uses internally is supplied only at run-time (at the time that an object of class C is instantiated).
Slide 48
Genericity (cont.)There are 3 possible solutions:
(1) Clone the old code and replace the int data with a Shape reference. (Pros? Cons?)
(2) Define the Linked-List data as a reference to Object. (Pros? Cons?)
(3) Define the Linked-List to be a generic class, which means that the list's data won't be assigned until run-time – Genericity.
Slide 49
Genericity (cont.)We could define the List class as follows:
class List<ListData> {
private Node<ListData> head;
...
public void print(){...}
}
The <ListData> is a generic class argument whose actual “value” will be supplied only at run-time.
If we instantiate a List object and call the method print – we now make fine use of polymorphism, since when it is defined in a generic class, we don't know what the exact type will be.
This requires that every type we use will have a print method defined
Slide 50
Genericity (cont.)As of Java 1.5 Genericity is an essential part of the language.
More on genericity in a few lessons.