03-JavaClasses - Computing Fundamentals with Java 4-1 Rick...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Computing Fundamentals with Java 4-1 Rick Mercer Franklin, Beedle & Associates, 2002 ISBN 1-887902-47-3 Java Classes Presentation Copyright 2002, Franklin, Beedle & Associates Students who purchase and instructors who adopt Computing Fundamentals with Java by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact. 4-2 Oneclass constructing thre e diffe nt obje e with its own re cts, ach se of t value (state s ) 4.1 Classes Classes are — — — — picture: OOT A Managers' perspective, Dr. Taylor a collection of methods and data a blueprint used to construct many objects a great way to partition a software system Java's construct to implement any new type we can imagine 4-3 Abstraction Abstraction: — — act of using and/or understanding something without full knowledge of the implementation allows programmer to concentrate on essentials • how does a Grid's mover move? Not to worry • how does String substring work? Don't need to know • what algorithm does the sqrt method use? However, programmers often create new types — — We will work out the details First up: How to allow for messages to objects 4-4 4.2 Methods A Java class contains many methods, each of which has a method heading Method headings specify the number and types of arguments required There are two major components to a method: — — the method heading the block (a set of curly braces with the code that completes the method's responsibility) 4-5 Method Headings Sun uses method headings (and other things) to document methods so we know how to use them public String substring( int beginIndex, int endIndex ) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex-1. Thus the length of the substring is endIndex-beginIndex. Examples: "hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile" Parameters: beginIndex - the beginning index, inclusive. endIndex - the ending index, exclusive. Returns: the specified substring. 4-6 What method headings tell us Method headings provide the information needed to use it they show us how to send a message to instances of the class public String substring(int beginIndex, int endIndex) What does the method evaluate to? String − What is the method name? substring − How many arguments are required? 2 − What type of arguments are required? int — Example message String fullName = "Murphy, John"; String lastName = fullName.substring( 0, 6 ); 4-7 Parameters = Arguments The substring method requires two arguments in order to specify the portion of the string to return. When the message is sent, the argument 0 is assigned to the parameter named beginIndex and the argument 6 to the parameter name endIndex fullName.substring( 0, 6 ); public String substring( int beginIndex, int endIndex ) Implementation of the method is not shown here 4-8 Arguments / Parameters When a message is sent — — The first argument is assigned to the first parameter, second argument gets assigned to the second parameter,... If you do not supply the correct number and type of arguments, you get compiletime errors — Examples of errors fullName.substring( fullName.substring( fullName.substring( fullName.substring( "wrong type" ); 0, 6, fullName.length() ); ); 0.0, 6.0 ); 4-9 Method Headings public return­type method­name ( parameter­1, parameter­2, parameter­ n, ... ) General form of a Java method heading public says a method is known where objects are constructed return-type may be any primitive type, any class, or void A void method returns nothing — — therefore, a void method can not be assigned to anything also, you can not place a call to a void method in println parameters, which are optional, specify the number and type of arguments required in the message 4-10 Parameters General form of a parameter between ( and ) in method headings class-name identifier -orprimitive-type identifier Example method headings: public public public public public int length( ) // class String int equals( String anotherString ) // class String void withdraw( double amount ) // class BankAccount double readDouble( ) // class TextReader void move( int spaces ) // class Grid 4-11 Method Headings whether the method is available to the outside world • public methods are known in the block where constructed In summary, method headings provide these things: — — — — — return-type the kind of value a message evaluates to method-name that begins a valid method call parameter-list the number and type of needed arguments documentation describing what the method does Hopefully, the programmer who wrote the method documents them with useful information — Now go to Sun's JavaTM API for sample method headings http://java.sun.com/j2se/1.4.2/docs/api/ 4-12 The Method Body The method body is Java code enclosed within a block { } Curly braces contain the same things you saw in main — — — — variable declarations and initializations: int creditOne = 0; input and output messages: readInt, System.out.println construct objects: Grid g= new Grid(8,6,1,1,Grid.EAST) messages: g.turnLeft() Method bodies have access to the state of the object The "state" of an object is implemented as variables declared inside the class rather than a method body — more on these "instance" variables later 4-13 Design Decisions with class BankAccount more operations name some additional methods more state name some additional instance variables BankAccount could have had — — It was designed as an introductory example The design values (desired characteristics) were — small interface, simple, easy to relate to it's easier to remember "Smith" than "217051931" Did not use account numbers because — 4-14 What is "good" design? software that will be more easily maintainable software that can be reused in other applications software that runs very fast software that best manages limited memory software may get to market more quickly than the competitors even if errors exist, this is a tradition at certain places Design decisions may be based on making — — — — There are usually tradeoffs to consider — There is rarely a perfect design Design is influenced by many things 4-15 Is BankAccount "good"? In a real-world BankAccount, there would be many more operations: — — applyInterest, printMonthlyStatement, averageDailyBalance Choosing what operations belong to a class requires many design decisions business, savings, vacation, escrow, ... The design decisions are captured by a Java class There would be many more types of Accounts — But the simple class suits our purposes for now — 4-16 Putting it All Together in a Class Even though quite different in specific methods and state, virtually all classes have this in common: − − − − private instance variables store the state of the objects constructors initialize the state of an object some messages modify the state of objects some messages provide access to the state of objects 4-17 One General form of a Class public class class-name { //--instance variables private class identifier ; private primitive-type identifier ; public class-name ( parameters ) // Constructor {// Implementation } //--Methods public return-type method-name-1 ( parameters ) {// Implementation } public return- type method-name-N ( parameters ) {// Implementation } } 4-18 An example Class simplified public class BankAccount { //--instance variables private String my_ID; private double my_balance; public BankAccount(String initID, double initBalance ) { // Constructor to initialize the state my_ID = initID; my_balance = initBalance; } public void deposit(double depositAmount) // modifier { // Credit this account by depositAmount my_balance = my_balance + depositAmount; } public void withdraw(double withdrawalAmount) { // Debit this account by withdrawalAmount my_balance = my_balance - withdrawalAmount; } 4-19 class BankAccount continued previous three modify state, these three access state state public String toString( ) // access { return my_ID + " $" + my_balance; } public String getID() { return my_ID; } public double getBalance() { return my_balance; } } // End class BankAccount // access state // access state 4-20 Objects are a lot about Operations and State The methods declared public are the messages that may be sent to any instance of the class the objects The instance variables declared private store the state of the objects — private means no direct access from outside the class If you have 5,234 BankAccount objects, you'll have 5,234 IDs and 5, 234 balances. Every instance of a class has it own separate state — 4-21 The Unified Modeling Language (UML) class diagram -- another view of a class methods and state 4-22 Sample Messages public class TestAccount { public static void main( String args ) { double withdrawalAmount = 600.00; BankAccount anAcct; anAcct = new BankAccount( "Moss", 500.00 ); anAcct.withdraw( withdrawalAmount ); anAcct.deposit( 40.00 ); System.out.println( "Name: " + anAcct.getID( ) ); System.out.println( "$" + anAcct.getBalance( ) ); } } 4-23 Instance Variables these are the variables that are declared inside the class, but outside of the method bodies each instance of the class has its own set of instance variables with 954 objects you have 954 sets of instance variables all methods in the class have access to instance variables • and most methods will reference at least one of the instance variables the data and methods are related The state of an object is stored as instance variables — — — — when declared private, no one else can access the instance variables the state is encapsulated, nice and safe behind methods 4-24 Constructors a special method that initializes the state of objects gets invoked when you construct an object has the same name as the class does not have a return type • a constructor returns a reference to the instance of the class Constructor — — — — Assigning object references to reference variables Grid aGrid = new Grid( 10, 10, 5, 4, Grid.EAST ); String aString = new String( "Initial state" ); BankAccount anAcct = new BankAccount( "Katey", 10.00 JFrame window = new JFrame( "My Application" ); ); 4-25 Constructors General form: calling a constructor to construct and initialize an object class-name object-name = new class-name (initial-state); — — — class-name: name of the class object-name: any valid Java identifier initial-state: zero or more arguments supplied during instance creation. 4-26 Constructors A constructor uses the arguments initial-state to help initialize the private instance variables public BankAccount( String ID, double initBalance ) { my_ID = ID; my_balance = initBalance; } BankAccount anAcct; anAcct = new BankAccount( "Kellen", 123.45); 4-27 Methods that Access State Other methods return the current value of an object's data member, or return some information related to the state of an object aString.length( ) // aGrid.row( ) // anAccount.getBalance( aBook.getBorrower( ) aString.substring( 0, return the number of characters tell me where the mover is )// get current balance // tell me who has the book 3 ) // Get part of a string Some accessing methods simply return values of instance variables, others require some processing 4-28 return in non-void methods Java's return statement provide the means to return information, General form return expression ; When return executes, the value of expression replaces the message control returns to the message expression must match return type in method heading — — String return type means you must return a String double return type means you must return a double You can not return an expression from a void method 4-29 Returning Information An instance of BankAccount public String getID( ) { return my_ID; } public double getBalance( ) { return my_balance; } System.out.println( + anAcct.getID() + ": " + anAcct.getBalance( ) ); — Optional: Demo the relationship between messages and methods with a source level debugging tool such as JBuilder 4-30 Implementing Methods that Modify State Some methods modify (change) the state of an object: aGrid.move( 5 ); // The mover is 5 spaces forward anAccount.withdraw( 120.00 ) // Account balance has been reduced by 120.00 // Modify the state of any BankAccount object public void withdraw( double amount ) { // my_balance is an instance variable my_balance = my_balance + amount; } 4-31 Naming Conventions 1: Always use meaningful names 2: Always use meaningful names 3: Always use meaningful names Rules #1, 2, and 3: Rule #4 Constructors: Name of the class Verbs Nouns modifying methods: accessing methods: borrowBook withdraw length row nRows • could use getLength, getRow, getID, getBalance 4-32 public or private? at least for now When designing a class, do this — — declare constructors and methods public declare instance variables private Public messages can be sent from the block in which the object is declared Private state can not be messed up like this BankAccount myAcct = new BankAccount( "Me", 10.00 ); myAcct.my_balance = myAcct.my_balance + 999999.99; 4-33 Protecting an Object's State Access modes make operations available to clients and also protect the state Instance variables and methods are known as follows Access Mode public Where is the member known? From all methods of the class and in the block where the object was constructed in main, e.g. Known only in methods of the class private 4-34 Some Guidelines declare instance variables private after class definition declare constructors public no return type, no static! declare most methods public no static! • however, private helper methods are often useful Recommendations for writing your first classes: — — — — — look at examples in Chapter 4 as a coding pattern start thinking: "More than one file" • use one file to store the class (no main method) • use another file with main to test drive (or use) instances of the class. The test driver might only have a main method for now 4-35 Object-Oriented Design Guidelines a rule of thumb intended to help produce good objectoriented software Object-oriented design guideline — Example: When deciding what access users of a class should have to methods and instance variables OOD Guideline 4-1 All data should be hidden within its class Translation: make instance variables private 4-36 Why private? If my_balance were public, what is it after this? myAcct.my_balance = myAcct.my_balance - myAcct.my_balance; With my_balance private, compiletime error occurs You want programmers to use the methods — imagine the other things that occur during a real withdraw • write a transaction to a file • check for trying to withdraw more than balance Also, you can later change the class Also, programmers only need to know the methods 4-37 Cohesion within a class The methods of a class should be strongly related — don't put a blastOff method in BankAccount don't put double my_acceleration in BankAccount The instance variables should be strongly related — Cohesion means solidarity, hanging together Classes with high cohesion are a better design — the methods and data are related OOD Guideline 4-2 Keep related data and behavior in one place ...
View Full Document

Ask a homework question - tutors are online