Presentation is loading. Please wait.

Presentation is loading. Please wait.

Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.

Similar presentations


Presentation on theme: "Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and."— Presentation transcript:

1 Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and visibility modifiers basic programming concepts object oriented programming topics in computer science syllabus

2 unit 4 2 Principles of object-oriented programming H encapsulation: data is protected from “external” users H inheritance: properties and methods defined for a certain structures can be used by all structures defined as direct offspring H polymorphism: the same function call may invoke different code, depending on context

3 unit 4 3 What are objects? H We divide the system into several autonomous components (objects), each has a well defined role and interface. These objects interact to achieve the functionality of the whole system. H The components themselves can be further divided into smaller components (e.g., stereo system) H The use of objects eases the design and maintenance of complex systems.

4 unit 4 4 Advantages of modular systems: H Readability: system is easier to understand H Independence: we can change the implementation of one component, without affecting the others H Reusability: a component may be used later in other places; or, we may find components written by others that are suitable for our needs

5 unit 4 5 Modularity & Reusability H In order for our components to be reusable we should design them as: Autonomous - a component should be an autonomous entity, so it could work anywhere Abstraction - it should have a clear abstraction, so others can easily understand it’s behavior (know what to expect from it) Clear interface - it should have a clear interface so it will be easy to work with, and to maintain Documentation & Naming - without documentation and good naming for interface methods, no one will understand how to use it

6 unit 4 6 Objects H An object is characterized by its: State -- attributes (descriptive characteristics) BehaviorsBehaviors -- what it can do (or be done to it) H For example, consider an object “checking account”: The state of the account is the amount of money in it The behaviors of the account include money deposit and withdrawal The behavior of the account typically changes its state

7 unit 4 7 Classes H A class is a description of objects having the same attributes and behaviors: It is the model or pattern from which objects are created It can be thought of as a blueprint for the object H A class defines the characteristics associated with an object: state -- internal variables behaviors -- methods

8 unit 4 8 Example – the Coin class H coin is an object which contains one piece of data, the state variable face H behaviors are missing: what can we do to, and with, a coin? public class Coin { public final int HEADS = 0; public final int TAILS = 1; private int face; }

9 unit 4 9 Classes H A class contains data declarations and method declarations int face; char ch; Data declaration (state variables) Method declaration (behavior)

10 unit 4 10 Writing Methods H object behavior  list of methods H A method declaration specifies the code that will be executed when the method is invoked (or called)

11 unit 4 11 Example: the Coin Class  In the Coin class we could define the following data: face, an integer that represents the current face HEADS and TAILS, integer constants that represent the two possible states H We might also define the following methods: a flip method, to flip the coin a getFace method, to return the current face

12 public class Coin { public final int HEADS = 0; public final int TAILS = 1; private int face; //----------------------------------------------------------------- // Flips the coin by randomly choosing a face //----------------------------------------------------------------- public void flip () { face = (int) (Math.random() * 2); } //----------------------------------------------------------------- // Returns the current face of the coin as an integer //----------------------------------------------------------------- public int getFace () { return face; } }

13 unit 4 13 Using objects H Object are defined and use by other parts of the program H The application program is also an object

14 public class CountFlips { //----------------------------------------------------------------- // Flips a coin multiple times and counts the number of heads // and tails that result. //----------------------------------------------------------------- public static void main (String[] args) { final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin myCoin = new Coin(); // instantiate the Coin object for (int count=1; count <= NUM_FLIPS; count++) { myCoin.flip(); if (myCoin.getFace() == myCoin.HEADS) heads++; else tails++; } System.out.println ("The number flips: " + NUM_FLIPS); System.out.println ("The number of heads: " + heads); System.out.println ("The number of tails: " + tails); } }

15 unit 4 15 Expanding the Coin Class  Once the Coin class has been defined, we can use it again in other programs as needed H We can add methods and variables as needed; “old” application programs will still work; a program will not necessarily use every service provided by an object H For example, we will add the following methods: a Coin constructor, to set up the object a toString method, to return a string description for printing

16 public class Coin { public final int HEADS = 0; public final int TAILS = 1; private int face; //----------------------------------------------------------------- // Constructor: sets up the coin by flipping it initially //----------------------------------------------------------------- public Coin () { flip(); } //----------------------------------------------------------------- // Flips the coin by randomly choosing a face //----------------------------------------------------------------- public void flip () { face = (int) (Math.random() * 2); }

17 //----------------------------------------------------------------- // Returns the current face of the coin as a string //----------------------------------------------------------------- public String toString(){ String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } //----------------------------------------------------------------- // Returns the current face of the coin as an integer //----------------------------------------------------------------- public int getFace () { System.out.print(toString()); return face; } }

18 unit 4 18 Writing Methods H When a method is invoked, the flow of control jumps to the method and executes its code H When complete, the flow returns to the place where the method was called and continues H The invocation may or may not return a value, depending on how the method was defined

19 unit 4 19 flip(); flip()Coin Method Control Flow H The called method could be within the same class, in which case only the method name is needed

20 unit 4 20 getFace toString toString(); myCoin.getFace(); CountFlips.main Method Control Flow H The called method could be part of another class or object

21 unit 4 21 Instance Data  The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own H A class declares the type of the data, but it does not reserve any memory space for it  Every time a Coin object is created, a new face variable is created as well H The objects of a class share the method definitions, but they have unique data space

22 unit 4 22 Instance Data face 0 coin1 flip() getFace() toString() int face; class Coin face 1 coin2

23 unit 4 23 Classes and Objects H There can be many different objects of a single class class Coin face flip() getFace()... HEAD flip() getFace()... TAIL flip() getFace()... TAIL flip() getFace()... Coin objects

24 unit 4 24 Data Scope H The scope of data is the area in a program in which that data can be used (referenced) H Data declared at the class level can be used by all methods in that class H Data declared within a method can only be used in that method H Data declared within a method is called local data H Example: Coin.face

25 unit 4 25 Creating Objects H The creation of a new object involves two things: 1.creating an empty object 2.initializing its state H Objects are always initialized when they are created  the state of the object is always defined by automatically activating the constructor method H The creation of some objects requires information specifying their initial state; for example, to create a new Coin we provide no additional information, the face is chosen randomly (via flip)

26 unit 4 26 Creating Objects  We use the operator new to create objects: new Coin(); new ChessPiece(“bishop”,”b”,1);  The operator new is followed by the name of the class from which we want to create a new instance, followed by a pair of parenthesis. If the creation requires parameters, we write them inside the parenthesis.

27 public class FlipRace { public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; // Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip(); // Print the flip results (uses Coin's toString method) System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2); // Increment or reset the counters count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; }

28 // Determine the winner if (count1 < GOAL) System.out.println ("Coin 2 Wins!"); else if (count2 < GOAL) System.out.println ("Coin 1 Wins!"); else System.out.println ("It's a TIE!"); } }

29 unit 4 29 References H Objects live in the main memory H When an object is created it is allocated a block of memory sufficient to hold all its state variables. The object occupies this block until it is destroyed. We have no control on the location in memory, where an object is created; it is just created somewhere. H In order to interact with an object, we must have some way to refer to it. We refer to an object by means of an object reference.

30 unit 4 30 Object references H An object reference is a special kind of value that identifies an object H Object references can be stored in variables: Coin myCoin = new Coin(); ChessPiece bishop1 = new ChessPiece(“bishop”,”b”,1); H The variable holds a reference to a particular object, it refers to this object; we can interact with the object through a variable that refers to it

31 unit 4 31 References: implementation H In practice, an object reference holds the memory address of an object H Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object ChessPiece bishop1 = new ChessPiece(“bishop”,”b”,1); bishop1

32 unit 4 32 References: declaration H The declaration of the object reference variable and the creation of the object are separate activities.  We declare a variable named bishop1 whose type is ‘a reference to ChessPiece’: ChessPiece bishop1;  bishop1 can store a reference to an instance of class ChessPiece. However, no ChessPiece object is created yet and the value of bishop1 is undefined!

33 unit 4 33 References: instantiation  We now create a new Chesspiece object and store the reference to it in the variable bishop1 : bishop1 = new ChessPiece(“bishop”,”b”,1); In a later stage of the program, bishop1 can be set to refer to another object, but it can only refer to a Chesspiece object.  There is a special null value that can be assigned to any reference variable to denote that this variable does not refer (currently) to any object. bishop1 = null;

34 unit 4 34 Interaction with objects: methods  We interact with an object by means of method invocation: bishop1.captured(); H Sometimes the invocation requires parameters: bishop1.move(i,j); H Some methods also have a return value: l = bishop1.locate();

35 unit 4 35 Assignment Revisited H The act of assignment takes a copy of a value and stores it in a variable H For primitive types: num2 = num1; Before num1 5 num2 12 After num1 5 num2 5

36 unit 4 36 Object Reference Assignment H For object references, assignment copies the memory location: bishop2 = bishop1; Before bishop1bishop2 bishop1 After bishop2

37 unit 4 37 Example: Reference Assignment Bucket bucket1 = new Bucket(4); bucket1.fill(); Bucket bucket2 = new Bucket(2); bucket2.fill(); bucket1 bucket2

38 unit 4 38 Example: Reference Assignment bucket1 = bucket2; int quantity = bucket1.getQuantity(); // quantity = 2 bucket1 bucket2

39 unit 4 39 Aliases H Two or more references that refer to the same object are called aliases of each other H One object (and its data) can be accessed using different variables H Aliases can be useful, but should be managed carefully H Changing the object’s state (its variables) through one reference changes it for all of its aliases

40 unit 4 40 Garbage Collection H When an object no longer has any valid references to it, it can no longer be accessed by the program H It is useless, and therefore called garbage H Java performs automatic garbage collection periodically, returning an object's memory to the system for future use H In other languages, the programmer has the responsibility for performing garbage collection

41 unit 4 41 OOP: Encapsulation H You can take one of two views of an object: internalinternal - the structure of its data, the algorithms used by its methods externalexternal - the interaction of the object with other objects in the program H From the external view, an object is an encapsulated entity, providing a set of specific services H These services define the interface to the object H The goal is abstraction: objects hiding details from the rest of the system bad example: year 2000 bug

42 unit 4 42 Encapsulation H An object should be self-governing H Any changes to the object's state (its variables) should be accomplished by that object's methods H We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state H The user, or client, of an object can request its services, but should not have to be aware of how those services are accomplished

43 unit 4 43 Encapsulation H An encapsulated object can be thought of as a black box H Its inner workings are hidden to the client, which only invokes the interface methods Client Methods Data

44 unit 4 44 Encapsulation & Visibility Modifiers H In Java, we accomplish encapsulation through the appropriate use of visibility modifiers H A modifier is a Java reserved word that specifies particular characteristics of a method or data value  We've used the modifier final to define a constant  Java has three visibility modifiers: public, private, protected, or none  We will discuss the protected modifier later

45 unit 4 45 Visibility Modifiers H We use the generic term member to describe a variable, a method or a constructor of the class H Members of a class that are declared with public visibility can be accessed from anywhere; service methods are declared public H Members of a class that are declared with private visibility can only be accessed from inside the class; usually instance variables are declared private H Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package

46 unit 4 46 Public Visibility H Members that are declared as public can be accessed from any class that can access the class of the member: they are part of the interface of the class  Example: the methods captured(), move() and locate() are part of the interface of class ChessPiece so we define them as public H We do not want to reveal the internal representation of the object’s data. So we usually do not declare its state variable as public (encapsulation)

47 unit 4 47 Private Visibility  A class member that is declared as private, can be accessed only by code that is within the class of this member  We hide the internal implementation of the class by declaring its state variables and auxiliary methods as private H Data hiding is essential for encapsulation

48 48 unit 5 // Example of illegal access class ChessPieceTest { public static void main(String[] args) { ChessPiece bishop1 = new Chesspiece(“bishop”,`b`,1); bishop1.state = “captured”; // this will not compile! }

49 unit 4 49 Changing the Implementation of a Class H Encapsulation allows us to change an implementation of a class without affecting other parts of the program. H Without encapsulation changes to implementation might “break” the program H Why would we want to change the implementation? Different implementations have different tradeoffs (e.g., space conservation, efficiency etc.)

50 unit 4 50 Visibility Modifiers: rules H No object's data should be declared with public visibility H Methods that provide the object's services (service methods) are usually declared with public visibility so that they can be invoked by clients H A method created simply to assist a service method (support method) is usually declared with private visibility


Download ppt "Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and."

Similar presentations


Ads by Google