av a
o J
Intr h 1)
(C
24-09-02 CMPT 213 Slides 01 © Dr. B. Fraser 1
What is this?
Why do we care?
24-09-02 2
One Name
●
Use this to..
– All objects are accessed by references.
– References are like pointers but
Java automatically dereferences when needed.
●
Give each idea one name
– Name field and constructor parameters the same.
– Ex: name both numStudents, vs using each of:
- studentCount public class Course {
- numStudents private int numStudents;
-n public Course(int numStudents) {
- numberStds [Link] = numStudents;
}
}
24-09-02 3
Pass by value
●
Java uses pass by value
– Passing a primitive type passes its value.
– Passing an object passes (by value)..
●
What this means
– When passed a primitive type, changes inside a
method have no effect outside the method.
– When passed an object, you can modify its state.
– You cannot change..
24-09-02 4
Multiple Object Reference
●
= on an object reference..
●
Example
GreetingsSelf phoneMsg = new GreetingsSelf("Einstein");
GreetingsSelf emailMsg = phoneMsg;
[Link]("Albert");
Variables on stack: Objects on heap:
Reference
phoneMsg
a GreetingsSelf
object
emailMsg
Name: Einstein
●
Automatic Garbage Collection
– Objects with no references to them are
automatically deleted.
24-09-02 5
Comments
●
JavaDoc:
commenting syntax used to generate documentation.
– on a class: above a class to describe purpose of class
– on a method: above a method (or field) to explain it
●
Suggest only using for API methods:
stable interface and requires solid documentation
for external users.
●
Commenting Rules (this course):
RULE 1:..
RULE 2: Name fields, methods, and parameters well so
..
24-09-02 CODE: Basic Java 6
Integrated Debugger
2. Run debug
1. Set breakpoint
4: Step program
F7: Step Into
F8: Step Over
F9: Resume
3. Use debugger
24-09-02 CODE DEMO: Debugger 7
What is the most over-used key word in C-
based languages?
Static!
24-09-02 8
Static
●
Static method
– Can be called on the class (no object required).
– Also called..
●
Static field
– Shared by all instances of the class.
– Also called..
– Often used for constants:
public static final int DAYS_PER_WEEK = 7;
●
Static local
– Not supported in Java.
24-09-02 CODE DEMO: [Link] 9
Static: What fails to compile?
public class StaticFun {
public static final int TARGET_NUM_HATS = 10;
private static int countNumMade = 0;
private int favNum = 0;
public static void main(String[] args) {
// WHICH OF THESE 4 LINES GIVES A COMPILE TIME ERROR?
changeFavNum(42);
displayInfo();
favNum = 10;
countNumMade = 9;
}
private void changeFavNum(int i) {
favNum = TARGET_NUM_HATS + i;
displayInfo();
}
private static void displayInfo() {
[Link]("TARGET_NUM_HATTS: " + TARGET_NUM_HATS);
[Link]("countNumMade: " + countNumMade);
[Link]("favNum: " + favNum);
}
}
24-09-02 10
Static Factory Method
●
Static Factory Method
– A..
– Like a constructor, but more flexible:
can give it a..
– A common..
●
Example
– In Pizza class:
public static Pizza makePizzaFromFile(File file) {
// Open file and read in values
// Create new Pizza object
// Return the Pizza
}
24-09-02 CODE: Child 11
Classes, Strings, Collections,
24-09-02 12
toString()
●
All Java objects have a toString() method
– All classes inherit from Object, which implements toString()
●
Returns a String object which..
– Used for debugging,..
– Recommended format:
@Override ..
public String toString() { @Override Annotation:
return getClass().getName() method overrides a
+ " [daField1=" + daField2 base class's method.
+ ", daField2=" + daField2 + "]"; (optional)
}
..
..getClass().getName() returns
class name of current object.
24-09-02 13
String Demo
static void demoStringConcat() {
String guess1 = "hello " + 42; What does each String
String guess2 = "hello " + 4 + 2;
String guess3 = 42 + "hello"; hold?
String guess4 = 4 + 2 + "hello";
String guess5 = new Integer(42).toString();
}
static void demoStringToNumber() { Also have:
String myInput = "42"; [Link](...)
int theValue = [Link](myInput); [Link](...)
[Link](...)
// Current date/time to string
Date now = new Date(); [Link]() gives:
String msg = "Currently " + now; Thu Jan 16 13:49:46 PST 2054
[Link](msg);
Date in [Link]
// Demo bad conversion
int oops = [Link]("Oops"); Throws
} NumberFormatException
24-09-02 14
Immutable
●
Strings are Immutable
Once created,..
– To “change” a string,..
●
Example
String msg = "H"; Creates 3 strings;
2 for garbage collection:..
msg = msg + "i";
msg += '!';
int count = [Link]();
●
Java does not support overloaded operators in
general, except for + and += on Strings.
– String still immutable, even with +=
24-09-02 15
Comparing Strings
●
Compare strings using..
String password = getDaUsersPassword();
if ([Link](“12345”)) {
[Link](“The air-shield opens.”);
}
●
Don't use ==
– == compares the..
if (password == yourGuess) {
String msg = “Wow! The program stores the ”
+ “password and your guess at the same ”
+ “memory location! Crazy!”;
[Link](msg);
}
24-09-02 16
UML
●
We will create the following classes in this section of
the slides.
24-09-02 17
List and ArrayList
●
Generic: works with..
●
Java includes many generic Collections.
– ArrayList implements the List interface and is backed by an array
(fast), and dynamically resizes.
List<Hat> hats = new ArrayList<>();
[Link](new Hat(“Blue”)); Don’t need to put <Hat>, the
for(Hat hat: hats) { type, because already
... specified on left-side.
}
●
Collections...
– To store primitives, use built in..
Integer, Long, Double, etc.
●
Why List and ArrayList?
– Design Principle: ..
24-09-02 CODE: PizzaOrder 18
When is your code done?
Coding Standards
24-09-02 19
Clean Code
●
Correct Code
– Implements the requirements.
– Has no (few) bugs.
●
Clean Code
–
– Conforms to..
–
–
●
Professionals write clean code.
24-09-02 20
Coding Standard
●
Course (and most companies) has a coding standard
(See web page)
– Your code must conform to this style guide.
– Each assignment may mention some specifics.
– Different than textbook:
●
K&R style bracket placement
●
Always include { }, even on one-line if/else
●
List fields before methods
●
Activity
– Read Coding Standard.
– Go through the Person class and clean it up.
24-09-02 CODE: BadStyle -- person, PersonTest 21
Summary
●
Use one clear name for an idea.
●
References to objects, everything pass-by-value.
●
Static makes class methods and class data.
– Static Factory Method for nameable constructor.
●
String: Immutable class for working with all strings.
●
Show classes with UML class diagram.
●
Coding standard enforced for clean code.
24-09-02 22