1 / 36

Introduction To Scientific Programming

Introduction To Scientific Programming. Chapter 5 – More About Objects and Methods. Overview – More, More, More !. More on Methods Referencing Static Methods (and Variables) Overloading More on Classes Wrapper Classes Constructors Groups of Classes - Packages More on Software Design

ordell
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 5 – More About Objects and Methods

  2. Overview – More, More, More ! • More on Methods • Referencing • Static Methods (and Variables) • Overloading • More on Classes • Wrapper Classes • Constructors • Groups of Classes - Packages • More on Software Design • Top-Down Design • Using Methods: Main/Helper/Class Interface

  3. I. More On Methods - Referencing • What are the possibilities? • Reference a method outside of its’ class • Reference a method from inside its’ class • Also must consider lifetime: • Reference a method before a class object has been created • Reference a method after a class object has been created

  4. When an Object Name Is Required • Public methods called outside and after an object definition has occurred simply require the object name to precede the method name. • For example: //Define object myOracle Oracle myOracle = new Oracle(); ... //dialog is a method defined in Oracle class myOracle.dialog(); ...

  5. When An Object Name Is Not Required • What if you want to use another method within the same class? • You would need objectName, but it doesn’t exist yet. • Answer: this. refers to the object that contains the current reference. Essentially, this. stands in for the object name. • You may either use this., or omit it, since it is presumed – i.e. methods called within an class definition file do not need to reference itself.

  6. Class Method Reference Example public class AddressBook { private final int MAX_ENTRIES = 100; //Fixed size limit of 100 private String BookName; private int numberOfEntries; … //--------------------------------------------------------------------------- // Method to find and display an entry in address book. //--------------------------------------------------------------------------- public boolean emptyBook() { if (this.numberOfEntries == 0) then //this. is optional return true; else return false; } //--------------------------------------------------------------------------- // 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++) { If !(emptybook) then //this. not used, o.k.! … } } }

  7. I.-B. Static Methods • You’ve thought/seen that some methods don't need an object to do their job: • Ex. a method to calculate the area of a circle of radius r • You should just pass the required parameter and return the area! • This is accomplished by using a static method. These methods are also called class methods. • Use the className that contains the method instead of an objectName to invoke it. Ex. Math.pow(x,3) • Declare static methods with the static modifier. Ex: public static double area(double radius) ...

  8. Uses for Static Methods • Static methods are commonly used to provide libraries of useful and related methods. • It is good practice to group static methods together, when possible. • Examples: • the Math class provided with Java • methods include pow, sqrt, max, min, etc. • the SavitchIn class for console Input • not automatically provided with Java • methods include readLineInt, readLineDouble, etc.

  9. The Matrix – Method Invocation

  10. Reconciling Static Methods and Method References • Watch out! A static method cannot reference an instance variable from it’s class • Likewise, a static method cannot automatically reference a non-static method from its or any other class. • The only exception to above is if the static method creates an object of the class to use as a calling object.

  11. Static Variables • By default, variables are dynamic. However, you can also create static variables with the reserved word static: static int numberOfInvocations = 0; • May be public or private but are usually private for the same reasons instance variables are (encapsulation). private static int numberOfInvocations = 0; • There is only one copy of a static variable and it can be accessed by any object of the class. • Can be used to let objects of the same class coordinate.

  12. Static Variables - II • Static variables defined at the class level are called Class variables. • If the variable is public, it can be referenced outside of the class by ClassName.variableName • Ex. Math.PI • A public static variable at the program class level has visibility throughout the program – i.e. a global variable.

  13. Definition: Privacy Leaks • Anytime you return an object from a method, you are giving back an address, not a value • the object is "unprotected" (usually undesirable) • The object looses it’s privacy – privacy leak • This applies to any class object (custom, wrapper, etc..) • One solution is to stick to returning primitive types (int, char, double, boolean, etc. • Best solution is called cloning … temp = passedObject.clone(); // method that clones (copies) object return temp; }

  14. I.-C. Overloading • You can have the same method name with more than one definitionwithin the same class! • Why do this? • Same calculations, different data types • Same object, different initialization conditions • Each definition must have a different “signature” • This means the same name but different argument types, or a different number of arguments, or a different ordering of argument types. • The return type is not part of the signature and cannot be used to distinguish between two methods.

  15. Signature • A method signature is the combination of method name and number and types of arguments, in order: • .equals(int) has a different signature than .equals(String) (same method name, different argument types) • myMethod(1)has a different signature than myMethod(1, 2) same method name, different number of arguments • myMethod(1,1.2)different signature than myMethod(1.2,1) (same method name and number of arguments, but different order of argument types.)

  16. Method Overloading Example • static double max(double a, double b)           Returns the greater of two double values. • static float max(float a, float b)           Returns the greater of two float values. • static int max(int a, int b)           Returns the greater of two int values. • static long max(long a, long b)           Returns the greater of two long values.

  17. It’s a Complicated World – Potential Issues with Overloading • If you accidentally use the wrong data type as an argument, you can invoke a different method. • If Java does not find a signature match, it attempts some automatic type conversions, e.g. int to double. Hence, an unwanted version of the method may execute. • Finally, you cannot have two methods that only differ in return type. This will produce an error: public double getWeight(); public float getWeight();

  18. II. More On Classes - Wrapper Classes • Used to wrap primitive types in a class structure • All primitive types have an equivalent class • The class includes useful constants and static methods (including conversion back to primitive type)

  19. Wrapper class example - Integer • Declare an Integer class variable: Integer n = new Integer(); • Convert the value of an Integer variable to its primitive type, int: int i = n.intValue(); //intValue returns an int • Some useful Integer methods/constants: • Integer.MAX_VALUE,Integer.MIN_VALUE - maximum and minimum integer value the computer can represent • Integer.valueOf("123"),Integer.toString(123) to convert a string to an integer and visa versa

  20. Wrapper Class variables contain address of value variable declaration example:Integer n; variable declaration & init: Integer n = new Integer(0); assignment: n = new Integer(5); Primitive Type variables contain the value variable declaration example:int n; variable declaration & init.:int n = 0; assignment: n = 99; Usage of Wrapper Classes There are some important differences in the code using wrapper classes versus primitive types

  21. II.-B. Constructors • A constructor is a special method designed to initialize instance variables • Automatically called when an object is created using new: Integer n = new Integer(0); • Often overloaded - more than one per class! • You may have different versions to initialize all, some, or none of the instance variables • Each constructor has a different signature (a different number or sequence of argument types)

  22. Defining Constructors • Constructor headings have the same name as the class and do not include any reference to a return type or void. • A constructor with no parameters is called a default constructor. • If no constructor is provided, Java automatically creates a default constructor. • If any constructor is provided, then no constructors are automatically created by the compiler

  23. Constructor Programming Suggestions • In your custom Classes, include a constructor that initializes all instance variables. • Also, include a constructor that has no parameters (default constructor) • This overrides any automatic action by the compiler • Include overloaded versions of constructor to handle different initializations • Important note: you cannot call a constructor for an object after it is created • If you want to change values of instance variables after you have created an object, you should create a set method!

  24. Constructor Example - PetRecord public class PetRecord { private String name; private int age; //in years private double weight; //in pounds . . . public PetRecord(String initialName) { name = initialName; age = 0; weight = 0; } Initializes three instance variables: name from the parameter and age and weight with default initial values. Sample use: PetRecord pet1 = new Pet("Eric");

  25. You Can Use Other Methods in a Constructor … public PetRecord(String initialName, int initialAge, double initialWeight) { set(initialName, initialAge, initialWeight); } … … private void set(String initialName, int initialAge, double initialWeight) { name = initialName; if ((initialAge < 0) || (initialWeight < 0)) { System.out.println(“Error: …”); } else { age = initialAge; weight = initialWeight; } }

  26. II.-C. Packages • A package is a way to group a collection of related classes • Think of a package as a library of classes • They do not have to be in the same directory as your program • The first line of each class in the package must bethe keyword package followed by the name of the package: package mystuff.utilities; • To use classes from a package in a program put an import statement at the start of the file: import mystuff.utilities.*; //all classes in directory

  27. A Package Name myjava is the base path myjava myjava.general.utilities is a specific package name general Classes in the package utilities AClass.java AnotherClass.java

  28. Package Naming Conventions • Use lowercase • The package name is the pathname with subdirectory separators ("/") replaced by dots • For example, if the package is in a directory named "utilities" in directory "mystuff", the package name is: imports myjava.general.utilities; imports myjava.general.*; imports myjava.*;

  29. Adding A Custom Package Path To JCreator

  30. III. Software Design – “Top-Down” Program Design • Step 1: Define potential objects and formulas needed • Step 2: Write a list of tasks, in pseudocode, that the program must do. • Step 3: Create a flow diagram • Step 4: For each task in the program, write a list of subtasks, in pseudocode, that the method must do. • Step 5: If you can easily write Java statements for any subtask, you are finished with that subtask. • Step 6: Repeat Steps 4. & 5. until done.

  31. Program Design Example – “Lab 3 Investment Account” • Step 1: Define Class InvestmentAccount w/ attributes of a savings account: balance, interest rate, deposit, contributions… Methods include open, deposit, add interest, close, … • Step 2: Program Greeting Open investment account #1 w/ deposit Open investment account #2 w/ deposit Run investment strategy #1 & compute rate of return Run investment strategy #1 & compute rate of return Compute difference and declare the superior strategy

  32. Lab 3 Investment Account – Step 3

  33. Lab 3 Investment Account – Step 4 • Step 4: … Open Investment Account #1 by instantiating an InvestmentAccount object with an account name, account number, initial deposit, … … Open Investment Account #2 by instantiating an InvestmentAccount object with an account name, account number, initial deposit, … … For investment strategy #1: for each of the 12 cycles, add $500 to account and compute new balance with interest …

  34. Programming Tip:Put A main In All Classes! • A main method can be used to test all members of any class. • It serves as test or “driver” code that can be left in a class and added to as you go. • If you change the name of your project/program to the name of just your custom class, it will execute the classes’ main method. • Otherwise, when the class is used to create objects, the main method is ignored.

  35. Diagnostic main • Main methods in Classes are referred to as diagnostic main methods. • Remember: Because main must be static, you can't automatically invoke non-static methods of the class. • You can however, invoke a non-static method in main if you create an object of the class.

  36. Summary – Further Additions To A Class • Diagnostic main methods. • set… method to change an instance variable (complement of get… method) • equals method to define equivalent objects • clone method to copy your object to a new object • Also, don’t forget writeOutput or toString to display contents of an object.

More Related