Docsity

Introduction to Objects - Semantics and Syntax - Slides | CS 241, Study notes of Computer Science

Toggle sidebar
bg1
1
Introduction to Objects:Introduction to Objects:
Semantics and SyntaxSemantics and Syntax
Defining an object
Creating an object
Instance variables
Instance methods
What What isis OOP?OOP?
zObject-oriented programming (constructing software using objects) and
procedural-oriented programming are different programming styles
– Its all about decomposing complexity
– Procedural: use methods for modularization and abstraction
– OOP: use objects for modularization and abstraction
zOOP approaches break down problems into program “things” (objects) that
parallel real
world
“
things
”
in the problem domain itself
30
Wright State University, College of Engineering
Dr. T. Doom, Computer Science & Engineering CS 241
Computer Programming II
parallel
real
-
world
things
in
the
problem
domain
itself
.
– We construct fields(instance variables) - things that the object “knows” or
represents a property or thing that the object “has”. Object state!
– We construct routines (methods) - things that the object can “do”.
x
y
Point
display()
name
maxSpeed
Boat
go()
suit
rank
Card
show()
name
fields
methods()
UML (Unified modeling language) diagrams
thing (generally a noun)
knows (generally nouns)
does (generally verbs)
Example: TETRISExample: TETRIS
zWhat are the game’s objects?
–
piece board
31
Wright State University, College of Engineering
Dr. T. Doom, Computer Science & Engineering CS 241
Computer Programming II
piece
,
board
zCapabilities: What do those objects know how to do?
– piece: be created, fall, rotate, stop at collision
– board:
zbe created, remove rows, check fo r end of game
zProperties: What attributes and components do they have?
– Piece: orientation, position, shape, color
– board: size, rows
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Introduction to Objects - Semantics and Syntax - Slides | CS 241 and more Study notes Computer Science in PDF only on Docsity!

Introduction to Objects:Introduction to Objects:

Semantics and SyntaxSemantics and Syntax

Defining an object Creating an object Instance variables Instance methods

WhatWhat isis OOP?OOP?

z Object-oriented programming (constructing software using objects) and procedural-oriented programming are different programming styles

  • Its all about decomposing complexity
  • Procedural: use methods for modularization and abstraction
  • OOP: use objects for modularization and abstraction z OOP approaches break down problems into program “things” ( objects ) that parallel real world “things” in the problem domain itself

30 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

parallel real-world things in the problem domain itself.

  • We construct fields ( instance variables ) - things that the object “knows” or represents a property or thing that the object “has”. Object state!
  • We construct routines ( methods ) - things that the object can “do”.

x y

Point

display()

name maxSpeed

Boat

go()

suit rank

Card

show()

name fields

methods() UML (Unified modeling language) diagrams

thing (generally a noun) knows (generally nouns) does (generally verbs)

Example: TETRISExample: TETRIS

z What are the game’s objects?

  • piece board

31 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

piece, board

z Capabilities: What do those objects know how to do?

  • piece: be created, fall, rotate, stop at collision
  • board:

z be created, remove rows, check for end of game

z Properties: What attributes and components do they have?

  • Piece: orientation, position, shape, color
  • board: size, rows

Classes and objectsClasses and objects

z A class is used to describe the name, fields, and methods for an object.

z A class is not an object. Its more like a blueprint for how to make one

and a set of instructions for what it does and how.

z Each object instance made from a class has the same fields (instance

variables), but the values of those fields ( state ) may differ from object

instance to object instance.

32 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z Analogy: Rolodex

  • A class is like a set of instructions for creating a blank Rolodex card.

It notes that you need to have an entry for name, phoneNumber, etc.

  • When you create an object (using the new operator) you create a

blank Rolodex card with those space for that information.

  • You then set those values for that specific card/object instance.
  • Another card/object instance would have the same type of

information, but not necessarily the same values

Creating/using an objectCreating/using an object

z It generally takes two classes to develop an object:

  • One to create the object
  • One to test/use the object (this one has main()). class Point {

int x; int y;

class PointTest { public static void main (String[] args) { Point p1 = new Point(); p1 x = 5;

33 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z Instance variables are declared inside a class, but not within a method.

  • These fields define state and last for as long as the object lives!

z Local variables are declared within a method and are not persistent

void display() { System.out.println( “(“ + x + ”,” + y +”)” ); } // end method display

} // end class Point

p1.x = 5; p1.display(); } // end method main

} // end class PointTest

UML for containment (HASUML for containment (HAS--A)A)

class Point {

int x; int y;

void display() { System.out.println( “(“ + x + ”,” + y +”)” ); } // d h d di l

class PointTest { public static void main (String[] args) { Point p1 = new Point(); p1.x = 5; p1.display(); } // end method main

} // d l i

34 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

} // end method display

} // end class Point

} // end class PointTest

PointTest main (args : String[]) : void

Point x : int y : int display() : void PointTest HAS-A Point Point is contained by PointTest

Arrays are objectsArrays are objects

z A variable can be assigned to any object of the appropriate type.

// Create an array referenced numbers.

int[] numbers = new int[10];

int[] digits = new int[500];

numbers = digits;

38 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

numbers digits;

z Both variables now reference the same object (NOT a copy)

z If an object has no references then object then the object is lost

  • it is “garbage” and will be “collected”

reference

reference

numbers

digits

Life and death on the heapLife and death on the heap

z The default value of a newly declared reference variable is null.

  • It doesn’t point at anything until you store a reference in it

z All new objects exist in an area of controlled memory called the heap.

z As long as an object has an active reference then it is reachable.

z An object that does not have an active reference is abandoned

  • In Java abandoned objects are eligible for garbage collection

39 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

  • In Java, abandoned objects are eligible for garbage collection

(automatic destruction)

  • In C++, objects must be explicitly destroyed by the program. Objects

that are abandoned can never be destroyed and cause a memory leak.

Point p1; At the end of this code segment: Point p2 = new Point(); - How many active references exist? p1 = p2; - How many reachable objects? p2 = new Point(); - How many abandoned objects? p1 = null; Consider drawing a diagram…

Passing objects as method argumentsPassing objects as method arguments

z Object references can be passed to methods like any data type.

int[] numbers = {5,10,15}; printList(numbers); …

numbers reference

40 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

void printList(int[] list){ for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); } } // end method printList

z What does this call by reference imply to changes made in clearList()?

list reference

void clearList(int[] list){ for (int i = 0; i < list.length; i++) list[i] = 0; } } // end method clearList

Arrays of objectsArrays of objects

z Array elements can contain primitive data types or references to objects.

  • We’ve seen this so far as arrays of String String[] nameList = {“Sam”, “Bobbie”, “Pat”, “Kim”, “Teri”};

reference

nameList[0]reference

nameList

String Sam

String Bobbie

41 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z An array of references can be made of any object type

Point[] pointList = {new Point(), new Point()};

reference reference reference reference

nameList[1]

nameList[0]

nameList[3]

nameList[2]

nameList[4]reference

String

String

String

Pat

Kim

Teri

Style:Style: JavadocJavadoc method headersmethod headers

  • goFish: Searches a hand for all cards of a named rank
  • @param rank The rank of card to be searched. Must
  • be passed as a String in the form “Ace”, “King”, …,“Two”
  • @param hand The hand of cards to be searched, found cards
  • will be removed!
  • @return All cards contained in hand that have the
  • specified rank (may be empty) */

42 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

ArrayList goFish(String rank, ArrayList hand) { ArrayList foundCards = new ArrayList(); for (Card theCard : hand) { if ( theCard.rank.equals(rank) ) { foundCards.add(theCard); hand.remove(theCard); } // end if found card of correct rank } // end for each card in hand return foundCards; } // end method goFish

Static: Class variablesStatic: Class variables

class Point { static int numPoints = 0; int x; int y; … } // end class Point

Point p1 = new Point(); p1.x = 7; p1.y = 8; Point.numPoints++; Point p2 = new Point(); p2.x = 3; p2.y = 1; p2.numPoints++; S i l ( 1 i )

43 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z Static variables:

  • a single memory location shared

by all instances of the class

  • one value per class, instead of

one value per instance

  • can be accessed w/o an instance

z p1.numPoints++ Vs. p1.x++ Vs. Point.x++ Vs. Point.numPoints++

System.out.println(p1.numPoints); (^) x 7 y^8

numPoints^2

x 3 y 1

p

p

Example:Example: CanvasPointCanvasPoint

z Say we want to use our “Point” class to keep track of things on

a graphics canvas of a specific standard size

x y

Point

display()

(0,0)

(800,600)

(800,0)

(0,600)

0 <- x -> 800

600

<-

y

->

0

47 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z What if someone using our CanvasPoint object does this:

  • CanvasPoint point1 = new CanvasPoint();
  • Point1.x = 1000;

z We need a way to protect our instance values from misuse from

an uninformed user (or an honest mistake)

  • Unfortunately, if someone has access to our variables, they

can do pretty much anything that they want to with them.

z We need a way to FORCE the user to check the values

x y

CanvasPoint

display()

UsingUsing mutatorsmutators (set methods)(set methods)

z We can create new methods whose only job is to provide

“checked” access to the variables.

public void setX(int xValue) { if (xValue < 0) { xValue = 0; } if (xValue > 800) { xValue = 800;

public void setY(int yValue) { if (yValue < 0) { yValue = 0; } if (yValue > 600) { yValue = 600;

48 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

x = xValue; } // end method setX

z These are called a mutator methods.

  • It changes the state of the object (instance variable value)

z What if later we decide to use a different sized Canvas?

z But can we force the user to use the mutator?

x y

CanvasPoint

display() setX(xValue : int) setY(iyValue : int)

y ; } y = yValue; } // end method setY

Hiding dataHiding data

z We can use access specifier to change to is allowed to

access an object’s variables and methods

  • public: any class can access our fields
  • private: only methods in the class can access its fields

CanvasPoint

public class CanvasPoint { private int x; i t i t

49 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z How can other classes look at (and use) the private values of

x and y?

-x -y +display() +setX(xValue : int) +setY(yValue : int)

private int y; public void setX (int xValue) { // our code here… } public void setY (int yValue) { // our code here… } } // end class CanvasPoint

UsingUsing accessorsaccessors (get methods)(get methods)

z We create methods whose only job is to access private

variables and return the result for use

-x -y

CanvasPoint

+display() : void +setX(xValue : int) : void +setY(yValue : int) : void

public class CanvasPoint { private int x; private int y; public void setX (int xValue)… public void setY (int yValue)…

50 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z These are called accessor methods.

+setY(yValue : int) : void +getX() : int public int getX () { +getY() : int return x; } public int getY () { return y; } } // end class CanvasPoint

EncapsulationEncapsulation

z This is the most important OO rule for style

  • Hide your data! Do not expose your variables
  • Mark all instance variables private
  • Mark access/mutators (getters/setters) public

z Always force the use of getters/setters.

  • Never expose your data!

51 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

  • Never expose your data!
  • Even if you do no checking right now, you may want to later
  • This means less code changing later! -x -y

CanvasPoint

+display() : void +setX(xValue : int) : void +setY(yValue : int) : void +getX() : int +getY() : int

Well encapsulated! But what is with xValue and yValue stuff?

Keyword:Keyword: thisthis

z Stylistically, it makes sense to use the logical name for

the method parameters that you use for the private

instance variables.

  • How do we deal with the namespace collision?

z Note: Overloading variables names is a feature!

-x -y

CanvasPoint

+display() : void +setX(x : int) : void +setY(y : int) : void +getX() : int +getY() : int

public class CanvasPoint { public class CanvasPoint {

52 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z The keyword this refers to the current object.

public class CanvasPoint { private x; … public void setX (int x) { // code to check valid x x = x; // semantic error! } … } // end class CanvasPoint

public class CanvasPoint { private x; … public void setX (int x) { //code to check valid x this.x = x; } … } // end class CanvasPoint

Default/Multiple ConstructorsDefault/Multiple Constructors

z Constructors have no return type and must have

the same name as the class

-x -y

CanvasPoint

+CanvasPoint() +CanvasPoint( x: int, y : int ) +display() : void +setX(x : int) : void +setY(y : int) : void +getX() : int +getY() : int

public CanvasPoint () {} // no-arg public CanvasPoint (int x, int y) { this.setX(x); this.setY(y); } // end constructor

56 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z The default constructor is a no-arg constructor

  • The compiler adds this for you if you do not

define you own constructor for the class

  • If you do define a constructor then the

compiler does not add this for you.

z You can overload the constructor method

  • Multiple constructors
  • Re-add a “default” constructor if you’d like

g () +toString() : String +equals(obj : CanvasPoint) : boolean +clone() : CanvasPoint

Discussion topic: Should programming languages provide destructors?