1 / 44

Introduction To Scientific Programming

Introduction To Scientific Programming. Chapter 4 – Defining Classes and Methods. Overview. Classes & Methods Classes Objects Methods Variables OOP - Encapsulation Revisits Scope Pass-by-value vs. Pass-by-address Object Assignment & Comparison Putting It All Together. Motivation.

sabina
Download Presentation

Introduction To Scientific 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. Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods

  2. Overview • Classes & Methods • Classes • Objects • Methods • Variables • OOP - Encapsulation • Revisits • Scope • Pass-by-value vs. Pass-by-address • Object Assignment & Comparison • Putting It All Together

  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. Code Statement • =,public,if, … • while,for, … • Operators • +,-, /,%, … • Primitive Data Types • - int,double, … Software Organizational Hierarchy Level of Organization • Package • groups of classes High • Class • group of objects • Object • data + method(s) • Methods • Action or value return • Code block • { … } Low

  5. I. Introducing Classes and Methods “Top-Down” A. Classes B. Objects C. Methods D. Variables OOP - Encapsulation … and then

  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, … • Aclass 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. 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. Are you finished? Yes 3 Console: 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

  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. Java Class File Structure imports Class Name Class Data/Variable Definitions Class Constructor (optional) Method 1 Method 2 Method n

  11. Summary Syntax Of A Class Definition /******************************************* * Class description * ******************************************/ public class Class_Name { <Instance variable definitions-accessible to all methods> //Method1 definitions of the form public returnType Method_Name1(type1 parmameter1, ...) { <statements defining the method> } //Method2 definitions of the form public returnType Method_Name2(type1 parmameter1, ...) { <statements defining the method> } }

  12. Book Example: Instances of A Class Class Definition First Instantiation: Object name: patsCar amount of fuel: 10 gallons speed: 55 miles per hour license plate: “135 XJK” Class Name: Automobile Data: float amount of fuel float speed String license plate Methods (actions): increaseSpeed: stop: filltank: getfuellevel: 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” Source Code Automobile patsCar, suesCar; Automobile ronsCar;

  13. Automobile fuel: double speed: double license: String + increaseSpeed(double howHardPress): void + stop(double howHardPress): void UML Class Diagrams Class Name Data Methods (actions) - private + public Graphical notation to summarize some of the main properties of a class. UML = Universal Modelling Language.

  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. 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. 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. 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. 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. voidMethod 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. 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. 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. 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) {<statements that define the main method> }}

  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. 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. 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. Example: Parameter Passing //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); } • What is the formal parameter in the method definition? • number1, number2 • What is the argument in the method invocation? • f1, f2

  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. 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. 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 Initializationfield 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. 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. 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. Your Book’s Encapsulation Diagram • Implementation: • Private instance variables • Private constants • Private methods • Bodies of public and private methods • Interface: • Comments • Headings of public methods • Public defined constants Programmer who uses the class A programmer who uses the class can only access the instance variables indirectly through public methods and constants.

  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:

  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:

  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. 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. Example: Class Type as a Method Parameter //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++) { <code that copies entries> } } • 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.

  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. 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. 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. 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) { <body of if statement> } … //this compares the characters in the strings if(firstLine.equals(secondLine) //this compares their values { <body of if statement> }

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

More Related