4-Objects and Object References
4-Objects and Object References
2
Variables and Types
• Two kinds of variables: primitive and object reference
• primitive variables hold fundamental types of values:
int, float, char,…
byte a = 7;
boolean done = false;
3
Primitive Data Types
• Three basic categories:
– Numerical: byte, short, int, long, float, double
– Logical: boolean (true/false)
– Character: char
à Primitive data are NOT objects
• wrapper type in order to treat primitive values
as objects:
– Integer, Float, Byte, Double, Character,…
• Integer count = new Integer(0);
– Provide utility functions: parseInt(), equals()…
4
Primitive Data Types
Primitive Minimum Maximum Wrapper
Size
Type Value Value Type
char 16-bit Unicode 0 Unicode 216-1 Character
byte 8-bit -128 +127 Byte
-215
+215-1
short 16-bit (-32,768) Short
(32,767)
-231 +231-1
int 32-bit Integer
(-2,147,483,648) (2,147,483,647)
-263 +263-1
long 64-bit (-9,223,372,036,854,775,808) (9,223,372,036,854,775,807)
Long
5
Object References – Controlling Objects
str str:String
value = “Hello”
str = new String("Hello");
object reference count = 5
the object
6
Object References
Dog myDog = new Dog();
7
Object Equality
• "==" and "!=" compares references (not objects)
to see if they are referring to the same object
Integer b = new Integer(10); a==b is true
Integer c = new Integer(10); b==c is false
Integer a = b;
if (b.equals(c)) { // true };
8
Object Equality
Method equals()
Integer m1 = new Integer(10);
• Pre-defined classes: Integer m2 = new Integer(10);
– Ready to use System.out.println(m1.equals(m2));
• User-created classes:
– equals() must be defined, otherwise, it always returns false
class MyInteger {
private int value;
public boolean equals (Object other) {
if (!(other instanceof MyInteger)) return false;
return (value == ((MyInteger) other).value);
}
}
9
Object's life on memory
• Objects are created in the heap memory
– a constructor is automatically called to initialize it
– the set of parameters determine which constructor to call
and the initial value of the object
10
Object's life on memory
• When an object is no longer used,
i.e. there's no more reference
to it, it will be collected and
freed automatically by Java
garbage collector
11
Object's life on memory
12
Object's life on memory
• In Java, un-used objects are automatically freed by
Java Virtual Machine (JVM), not manually by
programmers
13
Instance Variables vs. Local variables
Instance variables Local variables
• belong to an object • belong to a method
• located inside the object in the • located inside the method's
heap memory frame in the stack memory
• has the same lifetime as the • has the same lifetime as the
object method call
14
Instance Variables vs. Local variables
Heap memory Stack memory
object:Dog
name: “Bruno”
breed: null
size:
main’s stack frame
dog
class Dog {
Dog d = new Dog();
...
d.bark(3);
void bark(int numOfBarks) {
while (numOfBarks > 0) {
System.out.println("ruff");
numOfBarks--; An argument
}
}
16
Parameter Passing & Return Value
• The return value is copied to the stack, then to the
variable that get assigned (dogSize in this example)
d to
ie
class Dog { cop
e is
... alu
v
int getSize() { the
return size;
}
17
Parameter Passing & Return Value
18
Parameter Passing of Primitive Types
• pass-by-copy:
– Argument’s content is copied to the parameter
Dog d = new Dog();
d.bark(3);
19
Parameter Passing of Primitive Types
• A parameter is effectively a local variable that is
initialized with the value of the corresponding
argument
Dog d = new Dog();
d.bark(3);
20
Parameter Passing of Object References
• Object reference’s value is copied, NOT the
referred object y, m, d are of primitive data types.
They’ll take the values of the
class Date { passed parameter
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d;
}
public void copyTo(Date d) {
d.year = year; d is a reference.
d.month = month; d will take the values of the
passed parameter, which is
d.day = day; an object location
}
public Date copy() {
return new Date(day, month, year);
} return a reference to the newly
... created Date object.
} Again, it's a value, not the object
21
Parameter Passing of Object References
...
int thisYear = 2010;
Date d1 = new Date(thisYear, 9, 26);
class Date {
int year, month, day; y = thisYear;
public Date(int y, int m, int d) { m = 9;
d = 26;
year = y; month = m; day = d;
year = y;
} month = m;
public void copyTo(Date d) { day = d;
d.year = year;
d.month = month;
d.day = day;
}
public Date copy() {
return new Date(day, month, year);
}
...
}
22
Parameter Passing of Object References
...
Date d1 = new Date(thisYear, 9, 26);
Date d2 = new Date(2000, 1, 1);
d1.copyTo(d2);
class Date {
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d;
} d = d2;
d.year = d1.year;
public void copyTo(Date d) { d.month = d1.month;
d.year = year; d.day = d1.day;
d.month = month;
d.day = day;
}
public Date copy() {
return new Date(day, month, year);
}
...
}
23
Parameter Passing of Object References
...
Date d2 = new Date(2000, 1, 1);
Date d3 = d2.copy();
class Date {
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d;
}
public void copyTo(Date d) { Date temp =
d.year = year; new Date(d2.year, d2.month, d2.day);
d.month = month; d3 = temp;
d.day = day;
}
public Date copy() {
return new Date(year, month, day);
}
...
}
24
Method Overloading
• Methods of the same class can have the same
name but different parameter lists
class Dog { Dog d = new Dog();
...
void bark() { d.bark();
System.out.println("Ruff! Ruff!");
} d.bark(3);
void bark(int numOfBarks) {
while (numOfBarks > 0) {
System.out.println("ruff");
numOfBarks--;
}
}
}
25
Remind
Instance variables/methods belong to an object.
Thus, when accessing them, you MUST specify
which object they belong to.
26
How about this case?
class Dog {
int size; Which object does
String breed; size belong to?
String name;
void bark() {
if (size > 14) The object that owns
System.out.println("Ruff! Ruff!"); the current method –
else bark() or getBigger()
System.out.println("Yip! Yip!");
}
void getBigger() {
size += 5; Where is the object reference
} and dot notation?
}
27
The “this” reference
class Dog {
int size;
String breed; this reference was omitted
String name; in the previous slide
void bark() {
if (this.size > 14)
System.out.println("Ruff! Ruff!");
else
System.out.println("Yip! Yip!");
}
void getBigger() {
this.size += 5;
}
}
28
The “this” reference
• this : the object reference referring to
the current object – the owner of the current
method
• usage of this:
– explicit reference to object’s attributes and
methods
• often omitted
– parameter passing and return value
– calling constructor from inside another constructor
29
The “this” reference
class MyInteger {
private int value;
public boolean greaterThan (MyInteger other) {
return (this.value > other.value);
}
public boolean lessThan (MyInteger other) {
return (other.greaterThan(this));
}
public MyInteger increment() {
value++;
return this;
}
}
30
The “this” reference
class MyInteger {
private int value;
public MyInteger() {
this(0); Calls to MyInteger(int)
}
31
Input / Output
• In Java, input and output are often performed
on data streams
• A stream is a sequence of data. There are two
kinds of streams:
– InputStream: to read data from a source
– OutputStream: to write data to a destination
• Most I/O classes are supported in java.io
package
32
Standard I/O
• Three stream objects are automatically created when
a Java program begins executing:
– System.out : standard output stream object
• enables a program to output data to the console
– System.err : standard error stream object
• enables a program to output error messages to
the console
– System.in : standard input stream object
• enables a program to input data from the
keyboard
33
Standard output and error streams
34
Standard input
• System.in
– An InputStream object
– must be wrapped before use
• Scanner: wrapper that supports input of primitive
types and character strings
– next(): get the next word separated by white
spaces
– nextInt(), nextDouble(),…: get the next data item
– hasNext(), hasNextInt(), hasNextDouble(),…: check
if there are data left to be read
35
Standard input: Example
// import the wrapper class
import java.util.Scanner;
...
// create Scanner to get input from keyboard
Scanner sc = new Scanner(System.in);
// read a word
String s = sc.next();
// read an integer
int i = sc.nextInt();
36
Input from a text file: Example
Import required
classes
import java.util.Scanner;
import java.io.FileInputStream; To deal with errors such
import java.io.IOException; as file-not-found
...
public static void main(String args[]) {
try {
// create Scanner to get input from a file stream
Scanner sc = new Scanner(new FileInputStream("test.txt"));
} catch(IOException e) {
e.printStackTrace();
}
}
...
37
Write to a text file: Example
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
...
public static void main(String args[]) {
int i = 1; long l = 10;
try {
// create a printwriter to write output to a file stream
PrintWriter out = new PrintWriter(new FileWriter("test.txt"));
// write to file
out.println("Hello " + i + " " + l);
out.close();
} catch(IOException e) {
e.printStackTrace();
}
}
...
38
Command-line parameters
//CmdLineParas.java: read all command-line parameters
public class CmdLineParas {
public static void main(String[] args)
{
//display the parameter list
for (int i=0; i<args.length; i++)
System.out.println(args[i]);
}
}
}
39
Package
• A package is a grouping of related types (e.g.
classes, interfaces, etc.) to protect access or
manage namespace
• Two popular packages:
– java.lang: bundles the fundamental classes
(System, String, Math, etc.)
– java.io: bundles classes for input/output functions
(FileInputStream, PrintWriter, FileWriter, etc.)
40
Create a Package
• Task: create a package named “messagePkg”
contains the two following classes:
public class HelloMessage {
public void sayHello() {
System.out.println("Hello Everyone!");
}
}
41
Create a Package
• Step 1: declare the package which the class belongs to:
package messagePkg; package declaration with package name.
The rest of the file belongs to the same
public class HelloMessage { package
package messagePkg;
42
Create a Package
• Step 1: declare the package which the class belongs to:
package messagePkg;
43
Create a Package
• Step 2: Compile the classes of the same package:
javac –d <destination_folder> file_name.java
• Example:
javac –d . HelloMessage.java
javac –d . WelcomeMessage.java
or:
javac –d . HelloMessage.java WelcomeMessage.java
44
Use a Package
• Two ways: 1. Use the import statement to
make the name(s) in the package
import messagePkg.HelloMessage; available, once for all
45
Use a Package
• Compile
javac Hello.java
• Run
java Hello
46
47