Upgrade to Pro — share decks privately, control downloads, hide ads and more …

lecture09.pdf

Avatar for William Albritton William Albritton
August 27, 2014
82

 lecture09.pdf

Avatar for William Albritton

William Albritton

August 27, 2014
Tweet

Transcript

  1. Variable • A variable is a name for a place

    in memory where a value is stored String n1 = new String("Nami"); //n1 is a variable • Variables can be used to store an object’s address • An object’s address (reference) is the place in memory where an object is stored
  2. Data Fields • Data fields are variables used to store

    the data (attributes) of a specific object • Also called “instance variables” • Belong to an object • Declared (defined) in a class, but outside a method
  3. Data Field Example • For example, String objects have data

    fields (attributes) that store the characters and length of a String String n1 = new String("Hana"); //"Hana" is stored //in a data field. //4 is stored //in another data field.
  4. Defining Data Fields • When declaring (defining) data fields, put

    them outside all methods, but inside the class • Usually private, so data fields cannot be used by code outside the class • Data fields are global variables, so they can be used by any method in the same class as the data fields
  5. Example Code • See program Fraction.java public class Fraction{ private

    Integer numerator; private Integer denominator; public Fraction(Integer num, Integer den){...} //other methods public String toString(){...}
  6. Scope of Data Fields • The scope of a variable

    is where a variable is visible (where it can be used) • Scope refers to a program’s line numbers in a text file
  7. Scope of Data Fields • For data fields, the scope

    begins after the opening delimiter (curly bracket) of a class and ends at the closing delimiter (curly bracket) of a class • Scope of variables numerator and denominator are lines 12-235, as they can be used within any method in the Fraction.java program
  8. Comparison • Static Variables • Syntax to use a static

    variable outside a class: Class.VARIABLE • Example: double area = radius * radius*Math.PI; • Data Fields • Syntax to use a data field outside a class: cannot access directly • Example with accessor method: Integer num = f1.getNumerator();
  9. Comparison • Static Variables  Syntax to use a static

    variable inside a class: VARIABLE  Global scope, so can use in any method in the same class • Data Fields  Syntax to use a data field within a class: variable  Global scope, so can use in any method in the same class
  10. Comparison • Static Variables • Declaration has keywords “public static

    final” • By convention, all letters are capitalized • ALL_CAPS • Data Fields • Declaration only has keyword “private” (NO “static final”) • By convention, use “camel notation” • aCamelNotation
  11. Comparison • Static Variables • Example declaration: public static final

    String MESSAGE = new String("ERROR"); • Data Fields • Example declaration: private String name = new String("Fred");
  12. Comparison • Static Variables • Only have one copy of

    a static variable • Because classes do not use their static variables to create objects • Data Fields • Possible to have multiple copies of data fields • Because each object has one set of data fields
  13. Methods • Methods are used to define the behavior of

    a class • Used to get the object to do something • See the Java API for methods of the String class and many, many other classes
  14. Method Calls • To call (invoke) a method means to

    send a message (command) to an object • Syntax for (non-static) method call: variableName.methodName(); • Example: String upper = n1.toUpperCase();
  15. Comparison • Static Methods • Belong to a class as

    a whole • DO NOT access or modify the data fields of an object • Non-static Methods • Access or modify the data fields of an object
  16. Comparison • Static Methods • Method call syntax: Class.method() •

    Example: Double x = Math.pow(2.0,3.0); • Non-static Methods • Method call syntax: variable.method() • Example: String display = f1.toString();
  17. Comparison • Static Methods • Method definition has keyword “static”

    • Non-static Methods • Method definition DOES NOT have keyword “static”
  18. Method Call Terms String str = f1.toString(); method call variable

    variable of the same class as the method’s return type class
  19. Method Definition Terms public String toString() {String fractionString = numerator

    + " / " + denominator; return fractionString;} method prototype method body
  20. Method Definition Terms public String toString() { String fractionString =

    numerator + " / " + denominator; return fractionString; } access modifier return value return type method name local variable
  21. Method Call Examples • Java API class String method call

    String n1 = new String("Nami"); int length = n1.length(); //length is 4 • ICS 211 class Fraction method call Fraction f1=new Fraction(3,5); String output = f1.toString(); //output is "3 / 5"
  22. Method Definition • A non-static method has direct access to

    the class’s data fields • We can refer to the data fields by their names (see Fraction.java code) public String toString(){ String fractionString = numerator + " / " + denominator; return fractionString; }
  23. Access Modifier • The public access modifier allows access to

    a class’s methods from code outside the class • If the method’s access modifier is private, then we CANNOT use a class’s methods from code outside the class
  24. Access Modifier • In Fraction.java, because method greatestCommonDivisor() of class

    Fraction is private, we CAN ONLY call this method INSIDE the class • See reduceToLowestTerms() code Integer gcd = this.greatestCommonDivisor(numerator, denominator);
  25. Access Modifier • In FractionCalculator.java, because method greatestCommonDivisor() of class

    Fraction is private, we CANNOT call this method OUTSIDE the class • This code at the bottom of the main() method (on line #74) will NOT compile Fraction f = new Fraction(1,2); f.greatestCommonDivisor(1,2);
  26. Local Variables • The scope of local variables starts where

    the local variable is declared and ends at the last delimiter ("}") of the method • In the Fraction.java program, the scope of local variable fractionString starts at the declaration on line 45 and ends at the closing delimiter on line 50
  27. Comparison • Data Fields • Variables that are created within

    a class and outside all methods • Examples: numerator, denominator • Local Variables • Variables that are created within a method • Examples: fractionString, numerator2, denominator2, result
  28. Constructor • A constructor is a special method that initializes

    the values (data fields) of an object • The name of a constructor is the same as the name of its class • For example, the constructor’s name for class Fraction is “Fraction”
  29. Constructor Call • A call to a constructor must be

    preceded by keyword “new”, which creates space in memory (on the heap) for the object • Syntax: ClassName variable = new ClassName(); • Example: Fraction f1 = new Fraction(3, 4);
  30. Constructor Call • Classes that we write on our own

    can instantiate objects just like the classes from the Java API • Java API class String constructor String n2 = new String("Nami"); • ICS 211 class Fraction constructor Fraction f2=new Fraction(5,7);
  31. Constructor Call Terms Fraction f2 = new Fraction(5,7); (actual) parameters,

    also called arguments class variable constructor
  32. Constructor Definition • Just like other methods, a constructor definition

    has parameters • Unlike other methods, a constructor definition has neither a return type nor the keyword “void”
  33. Constructor Definition Terms public Fraction(Integer num, Integer den){ numerator =

    num; denominator = den; } access modifier constructor name parameter’s type (formal) parameter
  34. Parameters • The scope for parameters is similar to local

    variables • Starts at the method prototype, which is the first line of a method • Ends at the closing delimiter ("}") at end of the method
  35. Parameters • For example, in the Fraction.java program, the scope

    of parameter numeratorParameter in the constructor definition is from line 29 to line 38 • So we can only use the variable numeratorParameter from line 29 to line 38
  36. NullPointerException • A NullPointerException will happen whenever you try to

    call a method on a variable which is “null” • See NullPointerProgram.java code on the class web site • When you run the program, the exception will be thrown on line 17
  37. NullPointerException • If you do not initialize your data fields

    in your constructor, you may also get this exception • For example, set the data field denominator to “null” in the constructor in the Fraction.java program and then run the FractionCalculator.java program
  38. NullPointerException • To avoid forgetting to initialize my data fields

    in my constructor, I usually initialize my data fields when I first declare them private Integer numerator = new Integer(0); private Integer denominator=new Integer(1); • Of course, you can choose any way you wish to initialize your data fields
  39. Method toString() • Whenever a String is needed, the toString()

    method is automatically called • For example, when a variable is put in a print() or println() method
  40. Method toString() Fraction f1=new Fraction(5, 7); System.out.println(f1); //output is "5

    / 7" System.out.println(f1.toString()); //output is "5 / 7"
  41. Method toString() • Because all classes in Java are subclasses

    of class Object, which has method toString(), all classes automatically inherit the toString() method • See the Java API for class Object for the toString() method that is inherited by all classes in Java
  42. Method toString() • Unless you write the code for the

    toString() method for your class, your toString() method will output the default value for the toString() method, which looks funky • Try it yourself at home: comment out the toString() method in the Fraction.java program and run the FractionCalculator.java program
  43. Accessor Methods • Accessor methods are simple methods that return

    a data field • By convention, the name of an accessor method starts with “get” • Have a return value, but no parameters • Used to return data to the calling method
  44. Accessor Methods • Method call Fraction f1=new Fraction(5,7); Integer num=f1.getNumerator();

    //num is 5 • Method definition public String getNumerator(){ return numerator; }
  45. Mutator Methods • Mutator methods are simple methods that modify

    a data field • By convention, the method name starts with the word “set” • Have parameters, but no return value • Used to change the value of a data field
  46. Mutator Methods • Method call Fraction f1=new Fraction(5,7); f1.setNumerator(100); String

    str = f1.toString(); //str is "100 / 7" • Method definition public void setNumerator(Integer numeratorParameter){ numerator = numeratorParameter; }
  47. Other Methods • You can create any methods that you

    deem appropriate for any class • For example, the Fraction class has many more methods, such as add(), subtract(), divide(), multiply(), reduceToLowestTerms(), and greatestCommonDivisor()
  48. Task Manager • Before the next class, you need to:

    1.Do the assignment corresponding to this lecture 2.Email me any questions you may have about the material 3.Turn in the assignment before the next lecture 4.Admire your local scenery!