1 / 32

Basic Concepts of Object-Oriented Programming

Understand the basic concepts of object-oriented programming, including object state, behavior, identity, classes, inheritance, composition, encapsulation, and method and field declarations.

beatriceh
Download Presentation

Basic Concepts of Object-Oriented Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 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.

  2. 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: • Students • Graduate students • Undergraduate students • MS students • Ph.D. students

  3. 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: • 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.

  4. Relationship among Classes:Inheritance • A mechanism to organize classes by commonalities. • subclasses, specialization • superclass, generalization • Is-a relation • Example: • 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.

  5. Class Diagram: Inheritance

  6. Relationship among Classes:Composition • Has-a relation • Example: a student has a • address (type: Address) • faculty advisor (type: Faculty) • etc.

  7. Class Diagram: Composition

  8. 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)

  9. Class Declaration Syntax [ ClassModifiers ] class ClassName  [ extends SuperClass ]  [ implements Interface1, Interface2  ...] {  ClassMemberDeclarations}

  10. Class Visibility • publicAccessible everywhere. One public class allowed per file. The file must be named ClassName.java • default Accessible within the current package. • Other class modifiers: • abstractA class that contains abstract methods • finalNo subclasses

  11. Method and Field Declaration [ MethodModifiers ] ResultType  MethodName ( [ ParameterList ]  ) {  Statements} [ FieldModifiers ] Type  FieldName1 [ = Initializer1 ] ,   FieldName2 [ = Initializer2 ] ...;

  12. 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

  13. public 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 No Non-subclasses in  a different package Yes No No No Visibility

  14. 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); }

  15. Example: Coin.java public int getFace () { return face; } public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } }

  16. Example: CountFlips.java public 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); } }

  17. Example: FlipRace:java 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(); 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; }

  18. 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!"); } } }

  19. 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

  20. Special Methods • public boolean equals(Object o) • o1.equals(o2)versuso1 == 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

  21. 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; }

  22. 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(acctNumber + " " + fmt.format(amount)); } else { balance = balance + amount; } return balance; }

  23. 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; }

  24. Example: Account.java public 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)); }

  25. Example: BankAccount.java public 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));

  26. 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); } }

  27. StringTokenizer Class • separates a string into words (tokens) • white space as delimiters • Constructors: StringTokenizer(String str) StringTokenizer(String str, String delimiter) • Methods: boolean hasMoreTokens() String nextToken()

  28. Example: PigLatinTranslator.java import 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; }

  29. Example: PigLatinTranslator.java private 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; }

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

  31. Example: PigLatinTranslator.java private 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") ); }

  32. Example: PigLatin.java public 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")); } }

More Related