Download presentation
Presentation is loading. Please wait.
Published byArline Weaver Modified over 9 years ago
1
Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods
2
S.Horton/107/Ch. 4Slide 2 Overview I.Classes & Methods A.Classes B.Objects C.Methods D.Variables II.OOP - Encapsulation III.Revisits A.Scope B.Pass-by-value vs. Pass-by-address C.Object Assignment & Comparison IV. Putting It All Together
3
S.Horton/107/Ch. 4Slide 3 Motivation Wouldn’t it be very handy to have software already available that accomplish tasks that occur frequently? In fact, it is one of the central goals of software engineering to make software development fast, efficient, and error-free. This is accomplished by using or reusing software components that have already been developed, debugged, and tested. This leads us to an organizing structure that has been developed over time for most modern programming languages. In Java, this is called “Classes”.
4
S.Horton/107/Ch. 4Slide 4 Software Organizational Hierarchy Level of Organization Primitive Data Types - int, double, … Code Statement - =, public, if, … - while, for, … Operators +,-, /,%, … Object - data + method(s) Code block - { … } Methods - Action or value return Low Class - group of objects High Package - groups of classes
5
S.Horton/107/Ch. 4Slide 5 I. Introducing Classes and Methods “Top-Down” A. Classes B. Objects C. Methods D. Variables OOP - Encapsulation … and then
6
S.Horton/107/Ch. 4Slide 6 I.-A. Classes A class is an abstract, bundled (data + code) structure that programmers use to accomplish frequent and/or repetitive tasks. A class is a general blueprint for constructing specific instances of that blueprint. (In general, a Class itself does not execute). Examples: an Automobile class, an AddressBook class, a BankAccount class, a Matrix Class, a Complex class, … A class is made up of data and Methods (actions on the data). When a specific copy of a class is created (or instantiated), this specific instance is called an Object.
7
S.Horton/107/Ch. 4Slide 7 Example: String Class String is a class It contains data (a sequence of characters) It contains methods that perform actions and return values on a String type Coding convention for Classes: make first letter of name uppercase Note: Classes are additional (non-primitive) data types! A specific string is called a String object This is a specific instance of a class Each object inherits the structure of the class (data storage and methods)
8
S.Horton/107/Ch. 4Slide 8 Example: String Class Example: read characters typed in by user from the keyboard and output the number of characters entered String userInput; System.out.println(“Are you finished?”); userInput = SavitchIn.readLine(); System.out.println(userInput.length()); A String Class method Console: Are you finished? Yes 3
9
S.Horton/107/Ch. 4Slide 9 Class Source Files Each Java class definition should be placed in a separate file Use the same name for the class and the filename, except add ".java" to the file name Good programming practice: Start the class (and file) name with capital letter and capitalize inner words e.g. MyClass.java for the class MyClass Put all the classes you need to run a program in the same project directory
10
S.Horton/107/Ch. 4Slide 10 Java Class File Structure imports Class Data/Variable Definitions Class Name Class Constructor (optional) Method 1 Method 2 Method n
11
S.Horton/107/Ch. 4Slide 11 /******************************************* * Class description * ******************************************/ public class Class_Name { //Method1 definitions of the form public returnType Method_Name1(type1 parmameter1,...) { } //Method2 definitions of the form public returnType Method_Name2(type1 parmameter1,...) { } Summary Syntax Of A Class Definition
12
S.Horton/107/Ch. 4Slide 12 Book Example: Instances of A Class Class Name: Automobile Data: float amount of fuel float speed String license plate Methods (actions): increaseSpeed: stop: filltank: getfuellevel: First Instantiation: Object name: patsCar amount of fuel: 10 gallons speed: 55 miles per hour license plate: “135 XJK” Second Instantiation: Object name: suesCar amount of fuel: 14 gallons speed: 0 miles per hour license plate: “SUES CAR ” Third Instantiation: Object name: ronsCar amount of fuel: 2 gallons speed: 75 miles per hour license plate: “351 WLF” Class Definition Automobile patsCar, suesCar; Automobile ronsCar; Source Code
13
S.Horton/107/Ch. 4Slide 13 UML Class Diagrams Automobile fuel: double speed: double license: String + increaseSpeed(double howHardPress): void + stop(double howHardPress): void Methods (actions) Data Class Name - private + public Graphical notation to summarize some of the main properties of a class. UML = Universal Modelling Language.
14
S.Horton/107/Ch. 4Slide 14 B. Objects Objects are named variables that are instances of a class Note: the class is their type! Each object has both data and methods. Object data items are also called instance variables.
15
S.Horton/107/Ch. 4Slide 15 Objects II Invoking an object’s method means to call the method, i.e. execute the method Invoke an object's method with the dot operator objectName.method() Each object of a class has the same data items but can have different values All objects of the same class have the exact same methods
16
S.Horton/107/Ch. 4Slide 16 Instantiating (Creating) Objects Syntax: ClassName instance_Name = new ClassName(); Note the keyword new Examples that we have already used in our labs: Random generator = new Random(); DecimalFormat myFormat = new DecimalFormat("0.0000"); Public instance variables can be accessed using the dot operator: My favorites Math.PI – the most famous constant of them all Math.E – base of natural logarithms
17
S.Horton/107/Ch. 4Slide 17 C. Methods A method is a series of code statements and/or blocks that accomplish a task. Modern day methods are descendents of what used to be called “subroutines” or “procedures”. Methods now include the association with an object. Two basic kinds of methods: methods that return a value void methods that do some action but don’t return a value
18
S.Horton/107/Ch. 4Slide 18 Return Type of Methods All methods require that the return type be specified Return types may be: a primitive data type, such as char, int, double, etc. a class, such as String, AddressBook, etc. void if no value is returned You can use a method where it is legal to use its return type, for example the readLineInt() method of SavitchIn returns an integer, so this is legal: int next; next = SavitchIn.readLineInt();
19
S.Horton/107/Ch. 4Slide 19 void Method Example The definition of a writeOutput method of Class AddressBook : This assumes that the instance variables name, numberOfEntries, and updateDate have been defined and assigned values. This method performs an action (writes values to the screen) but does not return a value. //AddressBook class public class AddressBook() { String name; int numberOfEntries; Date updateDate; … public void writeOutput() { System.out.println(“Book = " + name); System.out.println(“Entries = " + numberOfEntries); System.out.println(“Last updated = " + updateDate"); }
20
S.Horton/107/Ch. 4Slide 20 value Method Example Methods that return a value must execute a return statement that includes the value to return For example: public int count = 0; //definition section //Method #n public int getCount() { return count; }
21
S.Horton/107/Ch. 4Slide 21 Method and Class Naming Conventions Use verbs to name void methods they perform an action Use nouns to name methods that return a value they create (return) a piece of data or an object Start class names with a capital letter Start method names with a lower case letter
22
S.Horton/107/Ch. 4Slide 22 A Very Special Method - The main Method A program written to solve a problem (rather than define an object) is written as a class with one method, main Invoking the class name invokes the main method Note the structure of our lab project programs: public class LabProject3 { public static void main(String[] args) { } }
23
S.Horton/107/Ch. 4Slide 23 Methods That Follow A Specific Structure Accessor methods—public methods that allow instance variables to be read Mutator methods—public methods that allow instance variables to be modified Mutator methods should always check to make sure that changes are appropriate. Providing mutator methods is much better than making instance variables public because a method can check to make sure that changes are appropriate.
24
S.Horton/107/Ch. 4Slide 24 Passing Parameters To A Method Methods can be passed input values Input values for methods are called parameters Each parameter and it’s data type must be specified inside the parentheses of the method heading these are called formal parameters The calling object must put values of the same data type, in the same order, inside the parentheses of the method name these are called arguments, or actual parameters
25
S.Horton/107/Ch. 4Slide 25 Primitive Data Types as Method Parameters There are two possible forms for method input parameters: Pass-by-value (a copy of the value is passed to method) Pass-by-address (the address of the variable is passed to method) Let’s look at “pass-by-value” first For all primitive data types, when the method is called, the value of each argument is copied to its corresponding formal parameter. Formal parameters are initialized to the values passed and are local to the method. Argument variables are not changed by the method! the method only gets a copy of the variable's value
26
S.Horton/107/Ch. 4Slide 26 Example: Parameter Passing What is the formal parameter in the method definition? number1, number2 What is the argument in the method invocation? f1, f2 //Invocation of the method... somewhere in main... f1 = SavitchIn.readLineFloat(); f2 = SavitchIn.readLineFloat(); System.out.println(“Closest squared integer = " + fmult(f1,f2)); … //Definition of a method to multiply two floats and return // the closest whole number. public int fmult(float number1, float number2) { float fvalue; fvalue = number1*number2; return Math.round(fvalue); }
27
S.Horton/107/Ch. 4Slide 27 D. Variables Variables declared in a Class are instance variables. Instance variables are created when the object is created and destroyed when the object is no longer used (this is the concept of lifetime). The AddressBook class has three instance variables: name, numberOfEntries and updateDate. It is always good practice to initialize variables when declared.
28
S.Horton/107/Ch. 4Slide 28 Local Variables and Blocks A block (a compound statement) is the set of statements between a pair of matching curly braces A variable declared inside a block is known only inside that block It is local to the block, therefore it is called a local variable When the block finishes executing, local variables disappear! References to it outside the block will cause a compile error Further, a variable name in Java can only be declared once for a method So, although the variable does not exist outside the block, other blocks in the same method cannot reuse the variable's name Warning: some other languages (e.g. C++) allow the variable name to be reused outside the local block.
29
S.Horton/107/Ch. 4Slide 29 More On Declaring Variables Declaring variables at the method level (outside all blocks) makes them available within all the blocks It is ok to declare loop counters in the Initialization field of for loops, e.g. for(int i=0; i <10; i++)… The Initialization field executes only once, when the for loop is first entered However, avoid declaring variables inside loops It takes time during execution to create and destroy variables, so it is better to do it just once for loops.
30
S.Horton/107/Ch. 4Slide 30 II. OOP - Encapsulation Object Oriented Programming (OOP) is the design of software using objects More than just defining objects, OOP allows us to do certain things that reduce development time, reduce errors, and improve maintainability. The first of these is the idea of “Encapsulation”. Simply stated, encapsulation is the idea that you hide all of the details of your classes from the outside “user ” (so they can’t mess it up).
31
S.Horton/107/Ch. 4Slide 31 Encapsulation II In Encapsulation: Classes protect their data (all instance variables are private) Assess to data is only through methods (Accessor/Mutator) (ex. public int getCount() ) Most methods are private (public only when necessary) Provides a public user interface so the user knows how to use the class descriptions, parameters, and names of its public methods the user cannot see or change the implementation
32
S.Horton/107/Ch. 4Slide 32 Your Book’s Encapsulation Diagram Programmer who uses the class Interface: Comments Headings of public methods Public defined constants Implementation: Private instance variables Private constants Private methods Bodies of public and private methods A programmer who uses the class can only access the instance variables indirectly through public methods and constants.
33
S.Horton/107/Ch. 4Slide 33 III.-A. Revisit: Variable Scope Let’s revisit the idea of scope for variables and methods. First, lets look at variables. Recall, scope is the visibility (or accessibility) of something to other parts of your code. For variables: Defined at:Variable/Object Class Level publicAccessible/can change inside as well as outside of class privateAccessible only within class and other class methods Method LevelAccessible only within method Code BlockAccessible only within block
34
S.Horton/107/Ch. 4Slide 34 Method Scope A method’s scope is established using the modifier public or private before the methods type Ex. public int getCount() For methods: Defined as:Method publicAccessible inside as well as outside of class privateAccessible only within class and by other class methods
35
S.Horton/107/Ch. 4Slide 35 III.-B. Revisit: Method Parameters (Pass-by-Address) What does a Java variable hold? It depends on the type of type, primitive type or class type A primitive type variable holds the value of the variable Class types are more complicated they have methods and instance variables A class type variable holds the memory address of the object the variable does not actually hold the value of the object In general, objects do not have a single value and they also have methods, so it does not make sense to talk about its "value"
36
S.Horton/107/Ch. 4Slide 36 Class Types as Method Parameters (Pass-by-value) For object variable names used as arguments in methods, the address (not the value) is passed! As a result, any action taken on the formal class type parameter in the method actually changes the original variable! Two ways to protect class parameters Don’t modify contents in a method “Clone” the formal parameter inside the method
37
S.Horton/107/Ch. 4Slide 37 Example: Class Type as a Method Parameter The method call makes otherObject an alias for s2, therefore the method acts on s2, the DemoSpecies object passed to the method! This is unlike primitive types, where the passed variable cannot be changed. //Class invocation AddressBook abFamily = new AddressBook(“Family", …); AddressBook abWork = new AddressBook(“Work”, …); … //Start by filling work address book with family addresses s1.makeEqual(s2); … //In class AddressBook, method definition makeEqual // that copies contents of AddressBook object public void makeEqual(AddressBook otherObject) { otherObject.name = this.name; otherObject.numberOfEntries = this.numberOfEntries; otherObject.updateDate = this.updateDate; for (int i=1; i<this.numberOfEntries; i++) { }
38
S.Horton/107/Ch. 4Slide 38 Comments on Example The call to method makeEqual makes otherObject an alias for abWork. Therefore the method changes abWork, the object passed to the method. This is unlike primitive types, where the passed variable cannot be changed. Use of reserved word this References the calling object
39
S.Horton/107/Ch. 4Slide 39 III.-C. Revisit: Object Assignment & Comparison Now that we know that an object’s variable name holds the address of the object, we are ready to examine assignment of objects: This transfers the address of abFamily to abWork. The net effect is that abWork now points to abFamily. Any information in abWork prior to this assignment is lost after the assignment! //Class invocation AddressBook abFamily = new AddressBook(“Family", …); AddressBook abWork = new AddressBook(“Work”, …); … abWork = abFamily;
40
S.Horton/107/Ch. 4Slide 40 Comparing Class Variables A class variable returns the memory address where the start of the object is stored. If two class variables are compared using ==, it is the addresses, not the values that are compared! This is rarely what you want to do! Use the class's.equals() method to compare the values of class variables.
41
S.Horton/107/Ch. 4Slide 41 Example: Comparing Class Variables //User enters first string String firstLine = SavitchIn.readLine(); //User enters second string String secondLine = SavitchIn.readLine(); … //this compares their addresses if(firstLine == secondLine) { } … //this compares the characters in the strings if(firstLine.equals(secondLine) //this compares their values { }
42
S.Horton/107/Ch. 4Slide 42 IV. Putting It All Together – An AddressBook Class //****************************************************************************/ //* AddressBook.java //* //* This class represents an electronic address book that can store contact //* information. Standard actions include adding a contact, deleting a contact, //* finding a contact, and displaying a contact //* //* Author: S. Horton //* Date created: 09/05/03 //****************************************************************************/ // //Import Date class import java.util.Date; // //Start of class defintion // public class AddressBook { private final int MAX_ENTRIES = 100;//Fixed size limit of 100 private String BookName; private int numberOfEntries; private Date updateDate; private String[] names = new String[MAX_ENTRIES]; private String[] phones = new String[MAX_ENTRIES]; …
43
S.Horton/107/Ch. 4Slide 43 IV. Putting It All Together – An AddressBook Class //--------------------------------------------------------------------------- // Class constructor that sets up a new AddressBook. Input is the name of // the address book. //--------------------------------------------------------------------------- public AddressBook(String name) { BookName = name; updateDate.getTime(); numberOfEntries = 0; } //--------------------------------------------------------------------------- // Method to add an entry to address book. //--------------------------------------------------------------------------- public void addEntry(String entryName, String workPhone) { numberOfEntries += 1; if (numberOfEntries > MAX_ENTRIES) { numberOfEntries -= 1; System.out.println("Error: max entries="+ MAX_ENTRIES + " reached, " + "cant add entry!"); } else { names[numberOfEntries] = entryName; phones[numberOfEntries] = workPhone; updateDate.getTime(); } …
44
S.Horton/107/Ch. 4Slide 44 IV. Putting It All Together – An AddressBook Class //--------------------------------------------------------------------------- // Method to delete an entry to address book. //--------------------------------------------------------------------------- public void deleteEntry(String entryName) { // Code to search names array for entryName // If found, remove it and then bubble up names to fill hole // If not found print error message } //--------------------------------------------------------------------------- // Method to find and display an entry in address book. //--------------------------------------------------------------------------- public void findEntry(String entryName) { // Code to search names array for entryName // If found, display it // If not found print error message } //--------------------------------------------------------------------------- // Method that copies contents of AddressBook object //--------------------------------------------------------------------------- public void makeEqual(AddressBook otherObject) { otherObject.BookName = this.BookName; otherObject.numberOfEntries = this.numberOfEntries; otherObject.updateDate = this.updateDate; for (int i=1; i<this.numberOfEntries; i++) { //code that copies entries }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.