Share
Embed
Annual Pro sale · Save $30
Have presentations of your own?
Share with private links, password protection, and more control over your work.
Transcript
51 slides
-
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 -
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 -
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. -
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 -
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(){...} -
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 -
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 -
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(); -
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 -
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 -
Comparison • Static Variables • Example declaration: public static final
String MESSAGE = new String("ERROR"); • Data Fields • Example declaration: private String name = new String("Fred"); -
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 -
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 -
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(); -
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 -
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(); -
Comparison • Static Methods • Method definition has keyword “static”
• Non-static Methods • Method definition DOES NOT have keyword “static” -
Method Call Terms String str = f1.toString(); method call variable
variable of the same class as the method’s return type class -
Method Definition Terms public String toString() {String fractionString = numerator
+ " / " + denominator; return fractionString;} method prototype method body -
Method Definition Terms public String toString() { String fractionString =
numerator + " / " + denominator; return fractionString; } access modifier return value return type method name local variable -
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" -
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; } -
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 -
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); -
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); -
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 -
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 -
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” -
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); -
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); -
Constructor Call Terms Fraction f2 = new Fraction(5,7); (actual) parameters,
also called arguments class variable constructor -
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” -
Constructor Definition Terms public Fraction(Integer num, Integer den){ numerator =
num; denominator = den; } access modifier constructor name parameter’s type (formal) parameter -
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 -
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 -
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 -
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 -
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 -
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 -
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" -
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 -
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 -
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 -
Accessor Methods • Method call Fraction f1=new Fraction(5,7); Integer num=f1.getNumerator();
//num is 5 • Method definition public String getNumerator(){ return numerator; } -
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 -
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; } -
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() -
Memory Defragmenter • Variables • Data fields • Constructors •
Accessor methods • Mutator methods -
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!