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.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Java Software Solutions
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Chapter 4: Writing Classes
INF 523Q Chapter 4: Writing Classes (Examples). Coin.java b //****************************************************************** b // Coin.java Author:
© 2006 Pearson Education Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
Inheritance. Class Relationships Composition: A class contains objects of other class(es) (actually, references to such objects) –A “has a” relationship.
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Writing Classes The programs we’ve written in previous examples have.
Writing Classes in Java
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Foundations of Program Design Writing Classes. 2 Objects b An object has: state - descriptive characteristicsstate - descriptive characteristics behaviors.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4 Writing Classes. We've been using predefined classes. Now we will learn to write our own classes to define objects Chapter 4 focuses on:  class.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
1 (c) elsaddik CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved2/48 Writing Classes We've been using predefined classes. Now we will learn.
Writing Classes (Chapter 4)
Writing Classes Chapter 5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
6. Object-Oriented Design Based on Java Software Development, 5 th Ed. By Lewis &Loftus.
CSE 1201 Object Oriented Programming Writing Classes.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
COS 312 DAY 7 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Due – 2 MIA Capstones proposals due – 1 group proposal for 4 student Assignment 3 Posted.
Wednesday –POD –I have updated grades in powerschool. If you have a zero for a lab grade, it probably means you didn’t DropItToMe. Please do so. –Slides.
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
INF 523Q Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Java – Methods Lecture Notes 5. Methods All objects, including software objects, have state and behavior. example, a student as an object has name, address,
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Writing Classes We've been using predefined classes. Now we will learn.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing.
COS 312 DAY 6 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Posted – Due Feb 22 prior to class Assignment 3 posted – March 5 Prior to class Capstones.
COS 312 DAY 7 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Not corrected yet – Will be done later today Capstones proposals Over due – 1 received.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
COS 312 DAY 8 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Corrected – Great results Capstones proposals Over due – 2 received Capstone progress.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Writing Classes Chapter 4.
Writing Classes We've been using predefined classes from the Java API. Now we will learn to write our own classes. Chapter 4 focuses on: class definitions.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Chapter 5 – Writing Classes
Chapter 5 – Writing Classes
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Outline Boolean Expressions The if Statement Comparing Data
Chapter 4 Writing Classes
Anatomy of a Method.
Writing Classes.
Chapter 4: Writing Classes
Presentation transcript:

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.

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

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.

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.

Class Diagram: Inheritance

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

Class Diagram: Composition

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)

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

Class Visibility public Accessible everywhere. One public class allowed per file. The file must be named ClassName.java default Accessible within the current package. Other class modifiers: abstract A class that contains abstract methods final No subclasses

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

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

Visibility publicprotectedpackageprivate The class itselfYes Classes in the same package Yes No Subclasses in a different package Yes No Non-subclasses in a different package YesNo

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 getFace () { return face; } public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; }

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

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

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

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

Special Methods public 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

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

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

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

Example: BankAccount.java public class BankAccounts { public static void main (String[] args) { Account acct1 = new Account("Ted Murphy", 72354, ); Account acct2 = new Account("Jane Smith", 69713, 40.00); Account acct3 = new Account("Edward Demsey", 93757, ); 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));

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

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()

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

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

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

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

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