Object-Oriented Programming
Objects and Classes in Java
Contents
• Instance variables vs. local variables
• Primitive vs. reference types
• Object references, object equality
• Objects' and variables' lifetime
• Parameter passing and return values
• Method overloading
• this reference
• Simple input/output
• Packages
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;
• reference variables hold references to objects
(similar to pointers)
Dog d = new Dog();
[Link] = "Bruno";
[Link]();
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
float 32-bit Approx range 1.4e-045 to 3.4e+038 Float
double 64-bit Approx range 4.9e-324 to 1.8e+308 Double
boolean 1-bit true or false Boolean
5
Object References – Controlling Objects
str str:String
value = “Hello”
str = new String("Hello");
object reference count = 5
the object
• There is actually no such thing as an object
variable
• There‘re only object reference variables
• An object reference variable represents a way to
access an object, something like a pointer
• Think of an object reference as a remote control
6
Object References
Dog myDog = new Dog();
Remind: References are not objects!
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;
• Use the equals() method to see if two objects
are equal:
Integer b = new Integer(10);
Integer c = new Integer(10);
if ([Link](c)) { // true };
8
Object Equality
Method equals()
Integer m1 = new Integer(10);
• Pre-defined classes: Integer m2 = new Integer(10);
– Ready to use [Link]([Link](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
Book b = new Book();
Book c = new Book(“Harry Potter”);
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
Book b = new Book();
Book c = new Book();
b = c;
There is no way to reach Book object 1.
It is ready to be collected.
11
Object's life on memory
Book b = new Book();
Book c = new Book();
b = c;
c = null;
Book object 1 is waiting to be de-allocated.
Book object 2 is safe as b is still referring to it.
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
public class DogTestDrive {
class Dog { public static void main(String
int size; [] args) {
String breed; Dog dog = new Dog();
String name; [Link] = "Bruno";
... [Link]();
} }
}
14
Instance Variables vs. Local variables
Heap memory Stack memory
object:Dog
name: “Bruno”
breed: null
size:
main’s stack frame
dog
public class DogTestDrive {
class Dog { public static void main(String
int size; [] args) {
String breed; Dog dog = new Dog();
String name; [Link] = "Bruno";
... [Link]();
} }
}
15
Parameter Passing & Return Value
• Parameter: used in method definition or declaration
• Argument: used in method call
A parameter
class Dog {
Dog d = new Dog();
...
[Link](3);
void bark(int numOfBarks) {
while (numOfBarks > 0) {
[Link]("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)
int dogSize = [Link]();
these types must match
d to
ie
class Dog { cop
e is
... alu
v
int getSize() { the
return size;
}
17
Parameter Passing & Return Value
• Two kinds of parameters:
– Primitive types
• parameter’s value is copied
• parameters can be constants, e.g. 10, “abc”,…
– Object references
• the reference's value is copied, NOT the
referred object
18
Parameter Passing of Primitive Types
• pass-by-copy:
– Argument’s content is copied to the parameter
Dog d = new Dog();
[Link](3);
class Dog { 0000011
0
... ed
copi
void bark(int numOfBarks) {
while (numOfBarks > 0) {
[Link]("ruff");
numOfBarks--;
}
}
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();
[Link](3);
class Dog { 0000011
0
... ed
copi
void bark(int numOfBarks) { something like
int numOfBarks = 3;
while (numOfBarks > 0) { happens at this point
[Link]("ruff");
numOfBarks--;
}
}
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) {
[Link] = year; d is a reference.
[Link] = month; d will take the values of the
passed parameter, which is
[Link] = 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;
[Link] = year;
[Link] = month;
[Link] = 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);
[Link](d2);
class Date {
int year, month, day;
public Date(int y, int m, int d) {
year = y; month = m; day = d;
} d = d2;
[Link] = [Link];
public void copyTo(Date d) { [Link] = [Link];
[Link] = year; [Link] = [Link];
[Link] = month;
[Link] = 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 = [Link]();
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 =
[Link] = year; new Date([Link], [Link], [Link]);
[Link] = month; d3 = temp;
[Link] = 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() { [Link]();
[Link]("Ruff! Ruff!");
} [Link](3);
void bark(int numOfBarks) {
while (numOfBarks > 0) {
[Link]("ruff");
numOfBarks--;
}
}
}
25
Remind
Instance variables/methods belong to an object.
Thus, when accessing them, you MUST specify
which object they belong to.
dot notation (.) public class DogTestDrive {
and public static void main(String [] args) {
the object Dog d = new Dog();
reference [Link] = "Bruno";
[Link](); access 'name' of the Dog
}
} call its bark() method
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
[Link]("Ruff! Ruff!"); the current method –
else bark() or getBigger()
[Link]("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 ([Link] > 14)
[Link]("Ruff! Ruff!");
else
[Link]("Yip! Yip!");
}
void getBigger() {
[Link] += 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 ([Link] > [Link]);
}
public boolean lessThan (MyInteger other) {
return ([Link](this));
}
public MyInteger increment() {
value++;
return this;
}
}
MyInteger counter = new MyInteger();
[Link]().increment(); // increased by 2
30
The “this” reference
class MyInteger {
private int value;
public MyInteger(int initialValue) {
value = initialValue;
}
public MyInteger() {
this(0); Calls to MyInteger(int)
}
public MyInteger(MyInteger other) {
this([Link]);
}
}
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 [Link]
package
32
Standard I/O
• Three stream objects are automatically created when
a Java program begins executing:
– [Link] : standard output stream object
• enables a program to output data to the console
– [Link] : standard error stream object
• enables a program to output error messages to
the console
– [Link] : standard input stream object
• enables a program to input data from the
keyboard
33
Standard output and error streams
• [Link] and [Link] can be used directly
[Link]("Hello, world!");
[Link]("Invalid day of month!");
34
Standard input
• [Link]
– 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 [Link];
...
// create Scanner to get input from keyboard
Scanner sc = new Scanner([Link]);
// read a word
String s = [Link]();
// read an integer
int i = [Link]();
// read a series of big integers
while ([Link]()) {
long aLong = [Link]();
}
36
Input from a text file: Example
Import required
classes
import [Link];
import [Link]; To deal with errors such
import [Link]; 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("[Link]"));
String s = [Link](); // read a word
int i = [Link](); // read an integer
while ([Link]()) { // read a series of big integers
long aLong = [Link]();
}
Open and close
the text file
[Link]();
} catch(IOException e) {
[Link]();
}
}
...
37
Write to a text file: Example
import [Link];
import [Link];
import [Link];
...
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("[Link]"));
// write to file
[Link]("Hello " + i + " " + l);
[Link]();
} catch(IOException e) {
[Link]();
}
}
...
38
Command-line parameters
//[Link]: read all command-line parameters
public class CmdLineParas {
public static void main(String[] args)
{
//display the parameter list
for (int i=0; i<[Link]; i++)
[Link](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:
– [Link]: bundles the fundamental classes
(System, String, Math, etc.)
– [Link]: 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() {
[Link]("Hello Everyone!");
}
}
public class WelcomeMessage {
public void sayWelcome() {
[Link]("Welcome ICTBI6 Class!");
}
}
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
public void sayHello() {
[Link]("Hello Everyone!");
}
}
package messagePkg;
public class WelcomeMessage {
public void sayWelcome() {
[Link]("Welcome ICTBI6 Class!");
}
}
42
Create a Package
• Step 1: declare the package which the class belongs to:
package messagePkg;
public class HelloMessage {
public void sayHello() {
[Link]("Hello Everyone!");
}
}
Declared as public so that
they can be used outside package messagePkg
package messagePkg;
public class WelcomeMessage {
public void sayWelcome(){
[Link]("Welcome ICTBI6 Class!");
}
}
43
Create a Package
• Step 2: Compile the classes of the same package:
javac –d <destination_folder> file_name.java
• Example:
javac –d . [Link]
javac –d . [Link]
or:
javac –d . [Link] [Link]
Try it by yourself to see how it works!
44
Use a Package
• Two ways: 1. Use the import statement to
make the name(s) in the package
import [Link]; available, once for all
public class Hello {
public static void main(String[] args) {
HelloMessage msg = new HelloMessage ();
[Link]();
}
} 2. Give the fully qualified name at
every call
public class Hello {
public static void main(String[] args) {
[Link] msg = new [Link]();
[Link]();
}
}
45
Use a Package
• Compile
javac [Link]
• Run
java Hello
Try it by yourself to see how it works!
46
47