Basic Concepts of OO An object has n
Basic Concepts of OO An object has n n n 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 n n A template for creating objects. Objects of the same class exhibit the same behavior. They may have different states.
Objects and Classes In 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: n n n Students Graduate students Undergraduate students MS students Ph. D. students
Objects and Classes In programming terms: A class is a software component that usually represents a real world class. The design of classes should utilize: n modularity n encapsulation A class defines certain common characteristics: n Data variables n 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.
Relationship among Classes: Inheritance A mechanism to organize classes by commonalities. n n subclasses, specialization superclass, generalization Is-a relation Example: n n 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.
Class Diagram: Inheritance
Relationship among Classes: Composition Has-a relation Example: a student has a n n n address (type: Address) faculty advisor (type: Faculty) etc.
Class Diagram: Composition
Class Declaration A class contains data (variable, field) declarations and method declarations n n n 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)
Class Declaration Syntax [ Class. Modifiers ] class Class. Name [ extends Super. Class ] [ implements Interface 1, Interface 2. . . ] { Class. Member. Declarations }
Class Visibility public Accessible everywhere. One public class allowed per file. The file must be named Class. Name. java default Accessible within the current package. Other class modifiers: n n abstract A class that contains abstract methods final No subclasses
Method and Field Declaration [ Method. Modifiers ] Result. Type Method. Name ( [ Parameter. List ] ) { Statements } [ Field. Modifiers ] Type Field. Name 1 [ = Initializer 1 ] , Field. Name 2 [ = Initializer 2 ]. . . ;
Encapsulation external view (client view): for the users of the class internal view(implementer view): for the developers of the class, visibility: n n public, protected, package (default), private
Visibility public protected package private The class itself Yes Yes Classes in the same package Yes Yes No Subclasses in a different package Yes No No Non-subclasses in a different package Yes No No No
Example: Coin. java public 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); }
Example: Coin. java public int get. Face () { return face; } public String to. String() { String face. Name; if (face == HEADS) face. Name = "Heads"; else face. Name = "Tails"; return face. Name; } }
Example: Count. Flips. java public class Count. Flips { public static void main (String[] args) { final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin my. Coin = new Coin(); for (int count=1; count <= NUM_FLIPS; count++) { my. Coin. flip(); if (my. Coin. get. Face() == my. Coin. 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); } }
Example: Flip. Race: java public class Flip. Race { public static void main (String[] args) { final int GOAL = 3; int count 1 = 0, count 2 = 0; // Create two separate coin objects Coin coin 1 = new Coin(); Coin coin 2 = new Coin(); while (count 1 < GOAL && count 2 < GOAL) { coin 1. flip(); coin 2. flip(); System. out. print ("Coin 1: " + coin 1); System. out. println (" Coin 2: " + coin 2); count 1 = (coin 1. get. Face() == coin 1. HEADS) ? count 1+1 : 0; count 2 = (coin 2. get. Face() == coin 2. HEADS) ? count 2+1 : 0; }
Example: Flip. Race: java // Determine the winner if (count 1 < GOAL) { System. out. println("Coin 2 Wins!"); } else if (count 2 < GOAL) { System. out. println("Coin 1 Wins!"); } else { System. out. println("It's a TIE!"); } } }
Method Overloading Two or more methods/constructors with the same name but different numbers or different types of parameters: void method. A(int i) void method. A(int i, int j) void method. B(int i) void method. B(float f) Avoid overloading
Special Methods public boolean equals(Object o) n o 1. equals(o 2) versus o 1 == o 2 w The equals() method tests the equality of two objects. w The == operator tests the identity of two objects. w When comparing two strings, use s 1. equals(s 2) instead of s 1 == s 2. public String to. String() n returns a string representation of the state of the object public void finalize() n invoked automatically by the Java runtimen just before an object is garbage-collected public void dispose() n invoked deliberately by the programmer when an object is no longer needed
Example: Account. java import java. text. Number. Format; public class Account { private Number. Format fmt = Number. Format. get. Currency. Instance(); private final double RATE = 0. 045; // interest rate of 4. 5% private long acct. Number; private double balance; private String name; public Account(String owner, long account, double initial) { name = owner; acct. Number = account; balance = initial; }
Example: Account. java public double deposit (double amount) { if (amount < 0) { // deposit value is negative System. out. println(); System. out. println("Error: . . . "); System. out. println(acct. Number + " " + fmt. format(amount)); } else { balance = balance + amount; } return balance; }
Example: Account. java public 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; }
Example: Account. java public double add. Interest () { balance += (balance * RATE); return balance; } public double get. Balance () { return balance; } public long get. Account. Number () { return acct. Number; } public String to. String () { return (acct. Number + "t" + name + "t" + fmt. format(balance)); }
Example: Bank. Account. java public class Bank. Accounts { public static void main (String[] args) { Account acct 1 = new Account("Ted Murphy", 72354, 102. 56); Account acct 2 = new Account("Jane Smith", 69713, 40. 00); Account acct 3 = new Account("Edward Demsey", 93757, 759. 32); acct 1. deposit (25. 85); double smith. Balance = acct 2. deposit (500. 00); System. out. println( "Smith balance after deposit: " + smith. Balance); System. out. println( "Smith balance after withdrawal: " + acct 2. withdraw (430. 75, 1. 50));
Example: Bank. Account. java acct 3. withdraw (800. 00, 0. 0); // exceeds balance acct 1. add. Interest(); acct 2. add. Interest(); acct 3. add. Interest(); System. out. println(acct 1); System. out. println(acct 2); System. out. println(acct 3); } }
String. Tokenizer Class separates a string into words (tokens) white space as delimiters Constructors: String. Tokenizer(String str) String. Tokenizer(String str, String delimiter) Methods: boolean has. More. Tokens() String next. Token()
Example: Pig. Latin. Translator. java import java. util. String. Tokenizer; public class Pig. Latin. Translator { public String translate(String sentence) { String result = ""; sentence = sentence. to. Lower. Case(); String. Tokenizer tokenizer = new String. Tokenizer (sentence); while (tokenizer. has. More. Tokens()) { result += translate. Word(tokenizer. next. Token()); result += " "; } return result; }
Example: Pig. Latin. Translator. java private String translate. Word (String word) { String result = ""; if (begins. With. Vowel(word)) { result = word + "yay"; } else if (begins. With. Prefix(word)) { result = word. substring(2) + word. substring(0, 2) + "ay"; } else { result = word. substring(1) + word. char. At(0) + "ay"; } return result; }
Example: Pig. Latin. Translator. java private boolean begins. With. Vowel (String word) { String vowels = "aeiou. AEIOU"; char letter = word. char. At(0); return (vowels. index. Of(letter) != -1); }
Example: Pig. Latin. Translator. java private boolean begins. With. Prefix (String str) { return (str. starts. With ("bl") || str. starts. With ("pl") str. starts. With ("br") || str. starts. With ("pr") str. starts. With ("ch") || str. starts. With ("sh") str. starts. With ("cl") || str. starts. With ("sl") str. starts. With ("cr") || str. starts. With ("sp") str. starts. With ("dr") || str. starts. With ("sr") str. starts. With ("fl") || str. starts. With ("st") str. starts. With ("fr") || str. starts. With ("th") str. starts. With ("gl") || str. starts. With ("tr") str. starts. With ("gr") || str. starts. With ("wh") str. starts. With ("kl") || str. starts. With ("wr") str. starts. With ("ph") ); } || || ||
Example: Pig. Latin. java public class Pig. Latin { public static void main (String[] args) { String sentence, result, another; Pig. Latin. Translator translator = new Pig. Latin. Translator(); do { System. out. println(); System. out. println("Enter a sentence (no punctuation): "); sentence = Keyboard. read. String(); 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. read. String(); } while (another. equals. Ignore. Case("y")); } }
- Slides: 32