SE 450 Fall 2001/2002
Week 2 Lecture Notes
Object Initialization
- Setting the initial state of the object
- Four methods:
- Explicit Initialization
- Default Values
- Constructors
- Initialization Block
Constructors
- same name as class
- no return type
- possible to have more than one
- Example:
public class Point {
private double x,y;
public Point() {
x = 0.0;
y = 0.0;
}
public Point(double init_x, double init_y) {
x = init_x;
y = init_y;
}
....
}
- Default (no-argument) constructor always provided,
except if you define another constructor.
Initialization Blocks
- executed before any constructors
- used to execute complicated initialization logic
- factors complicated logic out of multiple
constructors
Calling methods
- void methods may not return a value
- all control paths of non-void methods must return a
value
- variables local to a method do not get a default
value
- Parameters may be defined final to prevent them from getting reassigned in the
method body.
Variable, Object, Class,
Type
Variables have types, objects have classes.
- A variable is a storage location and has an associated
type.
- An object is a instance of a class or an
array.
- The type of a variable is determined at compilation time.
- The class of an object is determined at run time.
- Calls to methods are all resolved at run time.
import java.io.*;
public class foo {
public static void main (String[] s) {
test v1 = new test(1),
v2 = new test2(2);
v1.printit();
v2.printit(); } }
class test {
protected int x;
test() { x = 0; }
test(int y) { x = y; }
public void printit() {
System.out.print(x); } }
class test2 extends test {
private int y;
test2(int z) {
y = z;
x = y+1; }
public void printit() {
System.out.print(y); } }
Object Reference: this
You can use this inside a method
- It refers to the current object on which the method is invoked.
- It's commonly used to pass the object itself as a parameter
aList.insert(this);
- It can also be used to access hidden variables:
public class Point {
public int x, y;
public Point(int x, int y) {
this.x = x; this.y = y;
}
}
Static Fields
Static field: one per class, rather than one per object.
- Static fields are also known as class variables.
- Non-static fields are also known as instance variables.
class IDCard {
public long id;
protected static long nextID = 0;
public IDCard() {
id = nextID++;
}
}
Static Methods
A static method
- can only access static variables and other static methods;
- can not use this
class IDCard {
public long id;
protected static long nextID = 0;
...
public static void skipID() {
nextID++;
}
}
Final Variables
-
Final variables can't be changed.
-
Static final variables can be named constants.
class CircleStuff {
static final double pi = 3.1416;
}
Arrays
- declaration examples:
- float interestRates [];
interestRates = new float [100];
- varying syntaxes are allowed:
int[] ia = new int[3];
int ia[] = new int[3];
int[] ia = { 1, 2, 3};
float[][] mat = new float[4][4];
- Arrays are always bound-checked
- Array index starts from 0
for (int y = 0; y < mat.length; y++) {
for (int x = 0; x < mat[y].length; x++)
mat[x][y] = 0.0;
}
Wrapper classes
- values of primitive types are not objects
- Wrapper classes "wrap" the values of
primitive types into objects
- Boolean, Byte, Character, Double, Float, Integer,
Long, Short
- Methods of wrapper classes manipulate these values
- Example: Character.toUpperCase('a') returns 'A'
- Typical use: store primitives into collection classes
Strings
- String is a class, not an array of char's
- String is immutable
- String index starts from 0
- String constant: "A String constant"
- String concatenation: s1 + s2 and s1 += s2
- s.length(): the length of a string s.
- s.charAt(i): character at position i.
- = =
vs equals()
toString Method of Objects
The toString method converts objects to strings.
public class Point {
public int x, y;
...
String toString() {
return "(" + x + "," + y + ")";
}
}
Then, you can do
Point p = new Point(10,20);
System.out.println("A point at " + p);
// Output: A point at (10,20)
Exceptions
- Mainly an error-handling mechanism
- Two sources
- Run time exceptions that come from the JVM - don't
need try/catch block
- Other exceptions thrown by the program - need
try/catch block
throw ;
- exception-object must be an instance
of the Exception class (often an extension of Exception)
- Control returns to a catch statement
which catches that type of Exception.
- A method with a throw must be declared
to throw that type of Exception
public void Method_1() throws Method_1_Exception {
...}
Example of Exceptions
// Class average program with
// counter-controlled repetition
// version 3
import java.io.*;
public class Average {
static int counter = 1;
static int total;
static float average;
static final int CLASS_SIZE = 10;
public static void main( String args[] )
{
// processing phase
while ( counter <= CLASS_SIZE ) {
try {
showPrompt();
int grade = getGrade();
total = total + gradeToInt(grade);
counter++;
} catch (IOException e) {
System.out.print ( "\nTry again. ");
} catch (GradeException e) {
System.out.print ("\nIllegal grade entered. ");
}
}
average = averageGrades (total, counter-1);
outputResult(average);
}
public static void showPrompt ()
{
System.out.print( "Enter letter grade: " );
System.out.flush();
}
public static int getGrade () throws IOException
{
int grade = System.in.read();
System.in.skip( 1 ); // skip the newline character
return grade;
}
public static int gradeToInt(int grade) throws GradeException
{
if ( grade == 'A' ) return 4;
else if ( grade == 'B' ) return 3;
else if ( grade == 'C' ) return 2;
else if ( grade == 'D' ) return 1;
else if ( grade == 'F' ) return 0;
throw new GradeException ("Illegal grade entered: " + grade);
// should throw an exception
}
public static float averageGrades (int total, int count)
{
return total / (float) count;
}
public static void outputResult (float result)
{
System.out.println("Class average is " + result);
}
}
class GradeException extends Exception { }
Applets and their Methods
- All applets must subclass java.applet.Applet
- User customizes java.applet.Applet by overriding some
methods
- public void init(){...}
invoked when applet is initially loaded by browser
- public void start(){...}
invoked when entering the web page that contains the
applet
- public void stop(){...}
invoked when leaving the web page that contains the
applet
- public void destory(){...}
invoked when the applet is going to be destroyed by the
browser
- applet lifecycle (figure 3.4, pg. 110 in
Jia)
Applet examples