This is the lecture note of CS61B - Lecture 2.
Compilation
If you use an IDE(Integrated Development Environment), you can just click run
button and the program will be executed directly. But what happened under the hood? let's see a basic process of executing Java code.
Defining and Instantiating Classes
Let's define a Dog class only with a "makeNoise" method.
1 | public class Dog { |
Since there is no main
method, we cannot run the above code directly. To run it, we create another class called DogLauncher
.
1 | /** The DogLauncher class will test drive the Dog class. */ |
In the real world, different dogs yell differently. How to deal with it?
To make it more natural to represent the entire universe of dogs, we use the key feature of Java:
- classes can contain not just functions (a.k.a. methods), but also data.
- classes can be instantiated as objects.
The Dog class provides a bludeprint that all Dog objects will follow.
1 | public class Dog { |
1 | /** The DogLauncher class will test drive the Dog class */ |
Notice the method makeNoise
above is non-static now, meaning it should be invoked by an instance of the class.
Key differences between static methods and non-static (a.k.a. instance) methods:
- Static methods are invoked using the class name, e.g.
Dog.makeNoise( )
; - Instance methods are invoked using an instance name, e.g.
maya.makeNoise( )
; - Static methods can’t access “my” instance variables, because there is no “me”.
- for example:
d.weightInPounds
is ok,Dog.weightInPounds
will be wrong.
- for example:
Class can have a mix of static and non-static memebers (methods and variables).
1 | public class Dog { |
Notice the static variable binomen
. Although you can use an instance to call it, it's a bad style.
Remeber, if you declare a static member, use class instead of instance to access it, i.e. Dog.binomen
.
Arrays of Objects
To create an array of objects, you need 2 steps:
- First use the
new
keyword to create the array. - Then use
new
again for each object that you want to put in the array.
1 | Dogs[] dogs = new Dog[2]; |
Exercise
Finally, let's see an exercise.
Will the following program compile? If so, what will it print?
1 | public class DogLoop { |
The answer is:
- Yes, it can pass the compilation.
- It'll print:
- bark!
- wooof!
- wooof!
- NullPointerException (since Dog[3] is null)