32
Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied to the object). identity: determined at creation time. Class A template for creating objects. Objects of the same class exhibit the same behavior. They may have different states.

Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

  • View
    216

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Basic Concepts of OO

An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods

(operations that can be applied to the object). identity: determined at creation time.

Class A template for creating objects. Objects of the same class exhibit the same

behavior. They may have different states.

Page 2: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Objects and ClassesIn real world terms:

An object represents an individual entity or thing.Objects can be lumped together if they exhibit some common characteristics or behavior. Examples of classes in real world: Students Graduate students Undergraduate students MS students Ph.D. students

Page 3: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Objects and ClassesIn programming terms:

A class is a software component that usually represents a real world class. The design of classes should utilize: modularity encapsulation

A class defines certain common characteristics: Data variables behaviors

Each object that is created is an instance of a class.Each object has its own state, i.e., the values of the fields.

Page 4: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Relationship among Classes:Inheritance

A mechanism to organize classes by commonalities. subclasses, specialization superclass, generalization

Is-a relationExample: A graduate student is a student. A Master student is a graduate student. A Ph.D. student is a graduate student. An undergraduate student is a student.

Page 5: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Class Diagram: Inheritance

Student

GraduateStudent UndergraduateStudent

MasterStudent PhDStudent

Page 6: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Relationship among Classes:Composition

Has-a relationExample: a student has a address (type: Address) faculty advisor (type: Faculty) etc.

Page 7: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Class Diagram: Composition

-name : String-gpa : float

Student Faculty

-streetAddress : String-city : String-state : String-zipCode : String

Address

*1

* 1

Page 8: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Class Declaration

A class contains data (variable, field) declarations and method declarations Variables declared at the class level can

be used by all methods in that class Variables declared within a method can

only be used in that method A method declaration specifies the code

that will be executed when the method is invoked (or called)

Page 9: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Class Declaration Syntax

[ ClassModifiers ] class ClassName   [ extends SuperClass ]   [ implements Interface1, Interface2  ...] {   ClassMemberDeclarations }

Page 10: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Class Visibility

publicAccessible everywhere. One public class allowed per file. The file must be named ClassName.java defaultAccessible within the current package. Other class modifiers: abstract

A class that contains abstract methods final

No subclasses

Page 11: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Method and Field Declaration

[ MethodModifiers ] ResultType  MethodName ( [ ParameterList ]  ) {   Statements }

[ FieldModifiers ] Type  FieldName1 [ = Initializer1 ] ,    FieldName2 [ = Initializer2 ] ...;

Page 12: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Encapsulation

external view (client view): for the users of the class

internal view(implementer view): for the developers of the class,

visibility: public, protected, package (default), private

Page 13: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Visibilitypublic

protected

package

private

The class itself Yes Yes Yes Yes

Classes in the  same package 

Yes Yes Yes No

Subclasses in a  different package 

Yes Yes No NoNon-subclasses in  a different package

Yes No No No

Page 14: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: Coin.javapublic class Coin { public final int HEADS = 0; public final int TAILS = 1;

private int face;

public Coin (){ flip(); }

public void flip (){ face = (int) (Math.random() * 2); }

Page 15: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: Coin.java public int getFace () { return face; }

public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; }}

Page 16: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: CountFlips.javapublic class CountFlips { public static void main (String[] args) { final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin myCoin = new Coin(); for (int count=1; count <= NUM_FLIPS; count++) { myCoin.flip(); if (myCoin.getFace() == myCoin.HEADS) heads++; else tails++; } System.out.println(“Number flips: " + NUM_FLIPS); System.out.println("number of heads: " + heads); System.out.println("number of tails: " + tails); }}

Page 17: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: FlipRace:javapublic 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(); System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2); count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; }

Page 18: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: FlipRace:java // 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!"); } }}

Page 19: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Method Overloading

Two or more methods/constructors with the same name but different numbers or different types of parameters:

void methodA(int i) void methodA(int i, int j)

void methodB(int i) void methodB(float f)

Avoid overloading

Page 20: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Special Methodspublic boolean equals(Object o)

o1.equals(o2) versus o1 == o2 The equals() method tests the equality of two objects. The == operator tests the identity of two objects. When comparing two strings, use s1.equals(s2) instead of s1 == s2.

public String toString() returns a string representation of the state of the object

public void finalize() invoked automatically by the Java runtimen just before an

object is garbage-collected

public void dispose() invoked deliberately by the programmer when an object is no

longer needed

Page 21: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: Account.java

import java.text.NumberFormat;public class Account { private NumberFormat fmt = NumberFormat.getCurrencyInstance(); private final double RATE = 0.045; // interest rate of 4.5% private long acctNumber; private double balance; private String name; public Account(String owner, long account, double initial) { name = owner; acctNumber = account; balance = initial; }

Page 22: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: Account.javapublic double deposit (double amount) { if (amount < 0) { // deposit value is negative System.out.println(); System.out.println("Error: ..."); System.out.println(acctNumber + " " + fmt.format(amount)); } else { balance = balance + amount; } return balance;}

Page 23: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: Account.javapublic double withdraw(double amount, double fee) { amount += fee; if (amount < 0) { // withdraw value is negative System.out.println ("Error: ..."); } else if (amount > balance) { // withdraw value exceeds balance System.out.println ("Error: ..."); } else { balance = balance - amount; } return balance;}

Page 24: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: Account.javapublic double addInterest () { balance += (balance * RATE); return balance;}public double getBalance () { return balance;}public long getAccountNumber () { return acctNumber;}public String toString () { return (acctNumber + "\t" + name + "\t" + fmt.format(balance));}

Page 25: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: BankAccount.javapublic class BankAccounts { public static void main (String[] args) { Account acct1 = new Account("Ted Murphy", 72354, 102.56); Account acct2 = new Account("Jane Smith", 69713, 40.00); Account acct3 = new Account("Edward Demsey", 93757, 759.32); acct1.deposit (25.85); double smithBalance = acct2.deposit (500.00); System.out.println( "Smith balance after deposit: " + smithBalance); System.out.println( "Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50));

Page 26: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: BankAccount.java acct3.withdraw (800.00, 0.0); // exceeds balance acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println(); System.out.println(acct1); System.out.println(acct2); System.out.println(acct3); }}

Page 27: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

StringTokenizer Class

separates a string into words (tokens)white space as delimitersConstructors:StringTokenizer(String str)StringTokenizer(String str, String delimiter)

Methods:boolean hasMoreTokens() String nextToken()

Page 28: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: PigLatinTranslator.javaimport java.util.StringTokenizer;public class PigLatinTranslator { public String translate(String sentence) { String result = ""; sentence = sentence.toLowerCase(); StringTokenizer tokenizer = new StringTokenizer (sentence); while (tokenizer.hasMoreTokens()) { result += translateWord(tokenizer.nextToken()); result += " "; } return result; }

Page 29: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: PigLatinTranslator.javaprivate String translateWord (String word) { String result = ""; if (beginsWithVowel(word)) { result = word + "yay"; } else if (beginsWithPrefix(word)) { result = word.substring(2) + word.substring(0,2) + "ay"; } else { result = word.substring(1) + word.charAt(0) + "ay"; } return result;}

Page 30: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: PigLatinTranslator.javaprivate boolean beginsWithVowel (String word) { String vowels = "aeiouAEIOU"; char letter = word.charAt(0); return (vowels.indexOf(letter) != -1);}

Page 31: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: PigLatinTranslator.javaprivate boolean beginsWithPrefix (String str) { return (str.startsWith ("bl") || str.startsWith ("pl") || str.startsWith ("br") || str.startsWith ("pr") || str.startsWith ("ch") || str.startsWith ("sh") || str.startsWith ("cl") || str.startsWith ("sl") || str.startsWith ("cr") || str.startsWith ("sp") || str.startsWith ("dr") || str.startsWith ("sr") || str.startsWith ("fl") || str.startsWith ("st") || str.startsWith ("fr") || str.startsWith ("th") || str.startsWith ("gl") || str.startsWith ("tr") || str.startsWith ("gr") || str.startsWith ("wh") || str.startsWith ("kl") || str.startsWith ("wr") || str.startsWith ("ph") );}

Page 32: Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied

Example: PigLatin.javapublic class PigLatin { public static void main (String[] args) { String sentence, result, another; PigLatinTranslator translator = new PigLatinTranslator(); do { System.out.println(); System.out.println("Enter a sentence (no punctuation):"); sentence = Keyboard.readString(); System.out.println(); result = translator.translate (sentence); System.out.println("That sentence in Pig Latin is:"); System.out.println(result); System.out.println(); System.out.print("Translate another sentence (y/n)? "); another = Keyboard.readString(); } while (another.equalsIgnoreCase("y")); }}