Object Design
> Click or hit Control-Enter to run Example.main above
Scope and Name Resolution
public class Example {
// Both class and instance variables can be initialized
public static int classNum = 8;
public int objectNum = 4;
// objectNum shadows this.objectNum... I'd pick a better name
public void incrementObject(int objectNum) {
this.objectNum += objectNum;
classNum += objectNum;
}
// classNum shadows Example.classNum... I'd pick a better name
public static void incrementClass(int classNum) {
Example.classNum += classNum;
}
}
Let’s review our scoping rules.
-
Work to the left.
-
Remember that method parameters can shadow (or conflict with) class or instance variables.
> Click or hit Control-Enter to run Example.main above
final
and Constants
class Example {
/** The number of hours of sleep you should get per night. */
public static final int HOURS_PER_NIGHT = 8;
...
}
In Java a final
variable cannot be modified.
You usually see this done to establish useful constant values—which can be
either public
or private
> Click or hit Control-Enter to run Example.main above
Let’s Talk main
public class Example {
public static void main(String[] unused) {
System.out.println("How did I get here?");
}
}
You’ve been using and even writing main
methods?
But what is it?
Everything Has To Start Somewhere
public class Example {
public static void main(String[] unused) {
System.out.println("And this is it!");
}
}
-
When Java runs your program, execution has to start somewhere.
-
If a class has a
main
method Java can execute that class and begin the process of running a program. -
So every Java application starts in
main
somewhere.
But What About unused
?
public class Example {
public static void main(String[] unused) {
System.out.println("And this is it!");
}
}
But why is main
passed an array of Strings
s (that we usually ignore)?
(Short Demo)
Object Modeling
We frequently use Java objects to model real objects or entities.
Objects allow us to design software that deals with things in realistic and natural ways.
> Click or hit Control-Enter to run Example.main above
> Click or hit Control-Enter to run Example.main above
Announcements
-
MP3 is due Friday.
-
My office hours continue today at 11AM in the lounge outside of Siebel 0226. I’ll need to leave a bit early today.