005_oo_prog

clumpsmackoverΛογισμικό & κατασκευή λογ/κού

2 Δεκ 2013 (πριν από 3 χρόνια και 6 μήνες)

61 εμφανίσεις

OO Basics


CIS 2615

Copyright © 2000
-
2008 Shah Mumin

All Rights Reserved

OO Basics

2

OO Concepts

OBJECTS: An object is a software bundle that consists of
variables

and
methods
. It is modeled to real
-
life objets. Every object has
state

and
behavior
. For example, a car has
state

(color, engine horsepower,
number of tires, etc) and
behavior

(running, braking, accelerating,
slowing down, changing gears, etc).


CLASS: A class is a
blueprint

or prototype of an object consisting of
common properties (variables and methods). Once someone creates an
object out of a class blueprint, it becomes a real object or an
instance
.
Hence class
-
level variables are also called
instance variables
, and the
methods are called
instance methods
.


INHERITANCE
: In inheritance, a class inherits state and behavior from
a superclass. We will discuss inheritance in detail later.


OO Basics

3

OO Concepts

INTERFACE: Consists of method signatures and constants. There is
no implementation of any of the methods. The class that implements
an interface must implement them.


ENCAPSULATION (a.k.a. INFORAMTION HIDING): In OO
programming paradigm, the implementation is hidden from the
outside world.


Instead of direct access to the object data, they are provided through a
set of setter and getter methods. Also, access to data is restricted
through organizing classes into packages with proper access privileges
(public, protected, private, package local).

OO Basics

4

Class Member vs. Instance Member

Class members are methods and variables you declare with static
modifier. They are present when you call the class. We have seen
examples of the main() method to start a class. The main() method is
automatically loaded when you start the class. The same is true for
other static member variables we define.

package

com.javaclass.advanced;


public class

Employee {



private static

String

firstName;



public static void

setFirstName(
String

fname) {


firstName = fname;


}



public static void

printData() {


System
.out.println(
"First name: "

+ firstName);


}



public static void

main(
String
[] args) {


setFirstName(
"Shah"
);


printData();


}

}

Run
Employee.bat

OO Basics

5

Class Member vs. Instance Member

Because the setFirstName() and printData() methods are static, you can
call them from the main. The setFirstName() method can refer to the
class variable firstName because it is also static. As we have said, all
static variables and methods are loaded automatically.


Now, if we remove the static modifier, they become the instance
members.


When you create an instance of a class (e.g. using new keyword), the
runtime system creates one copy of each of the class's instance
variables for the instance along with the object itself.


Let’s look at the prototype of a class without any static members:

OO Basics

6

Class Member vs. Instance Member

package

com.javaclass.advanced;


public class

EmployeeA {



private S
tring

firstName;



public void

setFirstName(
String

fname) {


firstName = fname;


}



public void

printData() {


System
.out.println(
"First name: "

+ firstName);


}


}

Now, this class is a standalone program that can be called from
anywhere to access its accessible methods and fields. You do not
have to have a main in every class, however, you need a main()
method in the very first program you will call.

OO Basics

7

Class Member vs. Instance Member

If your program is only called by other programs, and never called
directly by the user, you do not need to have a main method. However,
you can place a main method in every class for testing purposes.


You should comment them out before placing them in production to
minimize memory usage.

package

com.javaclass.advanced;


public class

EmployeeB {



private S
tring

firstName;



public void

setFirstName(
String

fname) {


firstName = fname;


}



public void

printData() {


System
.out.println(
"First name: "

+ firstName);


}



public static void

main(
String
[] args) {


//setFirstName("Shah"); //ERROR: this method cannot be referenced from a static context


//printData(); //ERROR: this method cannot be referenced from a static context


}

}

Uncomment and compile from DOS (type/edit)

OO Basics

8

Class Member vs. Instance Member

Because none of the methods are static, you cannot call them directly
from your main. Before you can call of the members of your class, you
must create an instance of this class using the keyword new, and then
reference the newly created object using it’s name.

package

com.javaclass.advanced;


public class

EmployeeC {



private S
tring

firstName;



public void

setFirstName(
String

fname) {


firstName = fname;


}



public void

printData() {


System
.out.println(
“First name: “

+ firstName);


}



public static void

main(
String
[] args) {


EmployeeC

myEmp =
new

EmployeeC
();


myEmp.setFirstName(
“Shah”
);


myEmp.printData();


//if you want to create another Employee


EmployeeC

myEmp2 =
new

EmployeeC
();


myEmp2.setFirstName(
“Nishat”
);


myEmp2.printData();


}

}

Run
EmployeeC.bat

OO Basics

9

Class Member vs. Instance Member

You can create as many objects of this class you want, and reference
them using their instance (variable) name.


Your class is just a blueprint, but the instances are real objects. So, the
class Employee is just a blueprint to create a class, but when you use
new to create an instance of the Employee, you create a real object.


If you have a static member, you can call it directly without any
instance creation as we have done previously.

OO Basics

10

Default Constructor

When you compile your class, the compiler adds a default no
-
argument
constructor of the class if you do not supply one. The constructor is
used to create an instance of the class. In our previous example, we did
not have a constructor, but we can provide one

package

com.javaclass.advanced;


public class

EmployeeD {


private S
tring

firstName;



public

EmployeeD() {


}



public void

setFirstName(
String

fname) {


firstName = fname;


}



public void

printData() {


System
.out.println(
“First name: “

+ firstName);


}



public static void

main(
String
[] args) {


EmployeeD

myEmp =
new

EmployeeD
();


myEmp.setFirstName(
“Shah”
);


myEmp.printData();


EmployeeD
myEmp2 =
new

EmployeeD
();


myEmp2.setFirstName(
“Nishat”
);


myEmp2.printData();


}

}

Run
EmployeeD.bat

OO Basics

11

Class Template

Constructor is created using the class name but without any return
type. Constructors are neither methods nor members of the class.
They are just used to create the instance of the class.


Let’s look at a class template borrowed from the Java Tutorial:

OO Basics

12

Class Template

Now, let’s look at a diagram (also borrowed from the Java Tutorial) to
see all of the keywords and convention of declaring a class:

Example:

public class

Employee8SubClass
extends

Employee8
implements

Serializable

{

//body

}

OO Basics

13

Constructor Overloading

With the constructor, you can provide some initial data to load the
class.

In that case, you can create another constructor with different
signature (receives different number of parameters).

This is call constructor overloading. You can create as many
constructor as you need, but there should be a sanity check.

If you have too many different option, you should probably break
down the class in multiple classes.

Now, since we have two constructors, we can call either one of these
constructors. Be careful when you call the no
-
arg constructor,
because all of your Strings are null (number set to 0). If you do nay
operation in your variable, you will face the ugly
NullPointerException
.

OO Basics

14

Constructor Overloading

package

com.javaclass.advanced;


public class
Employee2 {



private

String

firstName;


private

String

lastName;


private

int

empNumber;



public

Employee2() {


}



public

Employee2(
String

fname,
String

lname,
int

enumber) {


firstName = fname;


lastName = lname;


empNumber = enumber;


}



public void

printData() {


System
.out.println(
"First name: "

+ firstName);


System
.out.println(
"Last name: "

+ lastName);


System
.out.println(
"Employee number: "

+ empNumber);


}



public static void

main(
String
[] args) {


Employee2

myEmp1 =
new

Employee2
();


myEmp1.printData();


Employee2

myEmp2 =
new

Employee2
(
"Shah"
,
"Mumin"
,
1234567890
);


myEmp2.printData();


}


}
//end of class

Run
Employee2.bat

OO Basics

15

Call Overloaded Constructor

We can overcome problem of not initializing data by initializing
them in the no
-
arg constructor.


You can directly initialize the variables in the constructor, or
preferably do it in one place by calling the other constructor


The keyword this refers to the current instance of the class. By using
the keyword this, you can call another constructor.


You can also mention any method or variable of the instance by using
this.

OO Basics

16

Call Overloaded Constructor

package

com.javaclass.advanced;


public class
Employee3 {


private

String

firstName;


private

String

lastName;


private

int

empNumber;



public

Employee3() {


this
(
""
,
""
,
0
);


}



public

Employee3(
String

fname,
String

lname,
int

enumber) {


firstName = fname;


lastName = lname;


empNumber = enumber;


}



public void

printData() {


System
.out.println(
"First name: "

+ firstName);


System
.out.println(
"Last name: "

+ lastName);


System
.out.println(
"Employee name: "

+ empNumber);


}



public static void

main(
String
[] args) {


Employee3

myEmp1 =
new

Employee3
();


myEmp1.printData();


Employee3

myEmp2 =
new

Employee3
(
"Shah"
,
"Mumin"
,
1234567890
);


myEmp2.printData();


}

}
//end of class

Run
Employee3.bat

OO Basics

17

Use of this

Sometimes, you might have many local and class variables in your
program. Using this clarifies that they are class variables.


You can also call your method using this. It would be useful when
you inherit another class and want to separate the method names of
the parent class and child class using this and super.


However, you cannot use this in a static context like from the main
method.


Use of the keyword “this” is useful in a method where you are
receiving parameters that are the same name as the class variables you
want to set them to.

OO Basics

18

Use of this

package

com.javaclass.advanced;


public class
Employee4 {


private

String

firstName;


private

String

lastName;


private

int

empNumber;



public

Employee4() {


this
(
""
,
""
,
0
);


}



public

Employee4(
String

firstName,
String

lastName,
int

empNumber) {


this
.firstName = firstName;


this
.lastName = lastName;


this
.empNumber = empNumber;


}



public void

printData() {


System
.out.println(
"First name: "

+
this
.firstName);


System
.out.println(
"Last name: "

+ lastName);


System
.out.println(
"Employee name: "

+ empNumber);


}



public static void

main(
String
[] args) {


Employee4

myEmp1 =
new

Employee4
();


myEmp1.printData();


Employee4

myEmp2 =
new

Employee4
("Shah", "Mumin", 1234567890);


myEmp2.printData();


}

}
//end of class

Run
Employee4.bat

OO Basics

19

Setter & Getter Methods

In your Java program, all of your instance variables should be
private unless you have real technical necessity to declare them
public.


For example, many static variables used to store system
information are public so that you can refer them directly.


A good software engineering approach is to keep all of your
implementation hidden and only expose data through methods so
that people cannot operate on them directly.


If you expose data directly, other modules might become
dependent on them. So, when you change your implementation
next time, you might inadvertently break several programs.


OO Basics

20

Setter & Getter Methods

Let’s look at an example.


In this class, we have 3 class variables that are declared private.
We will create a set of setter methods so that people can set their
variables. We can check the validity of data when someone wants
to set something. This also gives an opportunity to act when
someone is setting a piece of data after which some business logic
need to be performed.


We will also create a set of getter methods so that people can get
the value. This is useful because instead of exposing the data
directly, we are providing them through methods where we can
control what we send back.


If it is sensitive field, we might not provide a getter method to start
with. If data need to be modified before being sent, we can
modify it.

OO Basics

21

Setter & Getter Methods

package

com.javaclass.advanced;


public class

Employee6 {



private

String

firstName;


private

String

lastName;


private int

empNumber;



public

Employee6() {


this
(
""
,
""
,
0
);


}



public

Employee6(
String

fname,
String

lname,
int

enumber) {


this
.setFirstName(fname);
//optional this


setLastName(lname);


setEmpNumber(enumber);


}



public void

setFirstName(
String

fname) {


this
.firstName = fname;
//use of this optional


}



public

String

getFirstName() {


return

this
.firstName;
//use of this is optional


}




OO Basics

22

Setter & Getter Methods


public void

setLastName(
String

lname) {


lastName = lname;


}



public

String

getLastName() {


return

lastName;


}



public void

setEmpNumber(
int

enumber) {


empNumber = enumber;


}



public int

getEmpNumber() {


return

empNumber;


}



public void

printData() {


//you can use this keyword, optionally, to refer to class name


System
.out.println(
"First name: "

+
this
.firstName);
//optional this


System
.out.println(
"Last name: "

+ getLastName());


System
.out.println(
"Employee name: "

+
this
.getEmpNumber());


}



public static void

main(
String
[] args) {


Employee6

myEmp =
new

Employee6
(
"Nishat"
,
"Shah"
,
456356985
);


myEmp.printData();


myEmp.setFirstName(
"Amanda"
);


String

lname = myEmp.getFirstName();


System
.out.println(
"First name: "

+ lname);


}

}
//end of class

Run
Employee6.bat

OO Basics

23

Method Overloading

Sometimes, you might pass some values to a method to do certain
task. Sometimes, you set the data before and do the same task.


What do you do? Do you create two different methods?


Java provides method overloading to create multiple methods of the
same name.


The method signature (parameters) must be different in type.


You cannot have two functions of the same name receiving one String
parameter with different parameter names, for example.

OO Basics

24

Method Overloading

package

com.javaclass.advanced;


public class

Employee7 {


private

String

firstName;


private

String

lastName;


private int

empNumber;


public

Employee7() {


this
(
""
,
""
,
0
);


}


public

Employee7(
String

fname,
String

lname,
int

enumber) {


this
.firstName = fname;
//use of this is optional


lastName = lname;


this
.empNumber = enumber;


}


public void

printData() {


System
.out.println(
"First name: "

+
this
.firstName);
//optional this


System
.out.println(
"Last name: "

+ lastName);


System
.out.println(
"Employee name: "

+ empNumber);


}


public void
printData(
String

fname,
String

lname,
int

enumber) {


this
.firstName = fname;


lastName = lname;


empNumber = enumber;


printData();


}


public static void

main(
String
[] args) {


Employee7

myEmp =
new

Employee7
(
"Nishat"
,
"Shah"
,
456356985
);


myEmp.printData();


myEmp.printData(
"Nitol"
,
"Shah"
,
895653698
);


}

}
//end of class

Run
Employee7.bat

OO Basics

25

Pass
-
by
-
value: object copy

As we have mentioned before, there is no pass
-
by
-
reference Java since
we cannot manipulate memory like C/C++.


Everything is passed
-
by
-
value in Java. When you pass a primitive type
(such as int, double, float, etc), the value of the primitive type is passed
and the original variable remains the same. The receiving method may
change the value you have passed, but it has no effect on your original
variable.


When you pass objects, they are also passed
-
by
-
value with a twist.


Your original object remains same, but a copy of your object is passed
to the receiving method. If the receiving method updates the received
object using accessible members, your original object changes as well.

OO Basics

26

Pass
-
by
-
value: object copy

package

com.javaclass.advanced;


public class

EmployeeObjectPassing {


private

Employee6

testEmployee = new
Employee6
();



public

EmployeeObjectPassing() {


}



public void

updateEmployee(
Employee6

myEmployee) {


myEmployee.setFirstName(
"Shah"
);


myEmployee.setLastName(
"Mumin"
);


myEmployee.setEmpNumber(
12369852
);


}



public

Employee6

getEmployee() {


Employee6

emp = new
Employee6
();


updateEmployee(emp);


return

emp;


}



public static void

main(
String
[] args) {


EmployeeObjectPassing

tester =
new

EmployeeObjectPassing
();


//get Employee6 object


Employee6

emp = tester.getEmployee();


emp.printData();


tester.updateEmployee(emp);


emp.setFirstName("Nishat");


//we can also get the data directly


String

fname = emp.getFirstName();


System
.out.println("fname = " + fname);


}

}

Run
EmployeeObjectPassing.
bat

OO Basics

27

Package: Access Control

So far, we have created classes inside different packages just to keep
them organized into different sub
-
folders.


Packaging also controls access to member variables and methods. This
is one of most important reason for packaging in Java.


If a member variable or method is public in a class, anyone who has a
reference to it can access the member.


If members defined as protected, only the classes in the same package
can access it.


If there is no access modifier is defined for the member, then it is
package local (like friend in C++). Only classes from the same package
can access package local members of a class.


If a method is defined to be private, only the members of the class can
access it.


Let’s create a class with all different access modifiers:

OO Basics

28

Package: Access Control

package

com.javaclass.advanced;


public class

Employee8 {


private

String

empName;


public

Employee8() {


this
(
""
);


}


public

Employee8(
String

ename) {


this.empName = ename;


}


public void

printData() {


System
.out.println(
"Employee name: "



+
this
.empName);


}


private void

setEmpName(String fname) {


empName = fname;


}


protected void
setData(
String

ename) {


setEmpName(ename);


}


String

getEmpName() {


return

empName;


}


public static void

main(
String
[] args) {


Employee8

myEmp =
new

Employee8
(
"Nishat"
);


myEmp.printData();


myEmp.setEmpName(
"Fahmin"
);


myEmp.empName =
"Shah"
;


System
.out.println(
"myEmp.empName = "



+ myEmp.empName);


}

}
//end of class

package

com.javaclass.advanced;


public class

Employee8Tester {



public

Employee8Tester() {


}



public static void

main(
String
[] args) {


Employee8

emp =
new

Employee8
(
"Fahmin"
);


//of course, you can access a public method


//in any class


emp.printData();


//we can call a protected method because


//it is in the same package


emp.setData(
"Nishat"
);


//you can access any methods that is package local


//(no access privilege is defined)


//from within the same package


String

name = emp.getEmpName();


//you cannot access a private method of another class


//String name = emp.empName;


}

}

Now, we will have test harness to test this class.
Remember that this class also has a main method, which
is optional if you are not calling it directly.

Run
Employee8.bat

Run
Employee8Tester.bat

OO Basics

29

Package: Access Control

Now, let’s create a tester class outside out
package and test accessing protected and
package local methods. Since we are in two
different packages (we will use
com.javaclass.basic package), we name
them the same:

package

com.javaclass.basic;


import

com.javaclass.advanced.Employee8;


public class

Employee8Tester {


public

Employee8Tester() {


}


public static void

main(
String
[] args) {


Employee8

emp = new
Employee8
(
"Fahmin"
);


//of course, you can access a public method in any class


emp.printData();



//You cannot access a prtoected method


//outside the package


//only classes inside the same package can access it


//emp.setData("Nishat");



//you can access any methods that is package local


//from within the same package, not from outside that package


//String name = emp.getEmpName();



//you cannot access a private method in any other class


//String name = emp.empName;


}

}

package

com.javaclass.advanced;


public class

Employee8 {


private

String

empName;


public

Employee8() {


this
(
""
);


}


public

Employee8(
String

ename) {


this.empName = ename;


}


public void

printData() {


System
.out.println(
"Employee name: "



+
this
.empName);


}


private void

setEmpName(String fname) {


empName = fname;


}


protected void
setData(
String

ename) {


setEmpName(ename);


}


String

getEmpName() {


return

empName;


}


public static void

main(
String
[] args) {


Employee8

myEmp =
new

Employee8
(
"Nishat"
);


myEmp.printData();


myEmp.setEmpName(
"Fahmin"
);


myEmp.empName =
"Shah"
;


System
.out.println(
"myEmp.empName = "



+ myEmp.empName);


}

}
//end of class

Run
Employee8Tester2.bat

OO Basics

30

Package: Access Control

There is an exception to protected method access from outside the
package.


If another class from a different package subclass it, then he subclass
can access the protected members of the parent class.


Although we will learn inheritance in detail later, this chapter will
introduce you how to create a subclass from parent class.


The parent class is inherited using keyword extends in the class
definition, and the parent can be referred to as super.


How to add current directory to your CLASSPATH for compiling
multiple packages? Use the dot(.) to refer to the current directory


set CLASSPATH=%CLASSPATH%;C:
\
jdk1.4
\
lib
\
tools.jar;.;

OO Basics

31

Package: Subclass

package

com.javaclass.basic;


import

com.javaclass.advanced.Employee8;


public class

Employee8SubClass
extends

Employee8

{


Employee8SubClass() {


super
();
//calls constructor of parent to initialize


}


Employee8SubClass(
String

ename) {


//call the superclass constructor (Employee8)


super
(ename);
//passing data to parent class constructor


}


private void

accessPackageLocal() {


//We cannot access a method that is


//package
-
local in the parent class


//String name = super.getEmpName();


}


protected void

setParentData(
String

ename) {


//setData is a protected in the parent class,


//but we can access it


//since it is the parent of this class


super
.setData(ename);


//setData(ename);


//same as the previous call, you donot have to use super



//you can call the instance methods using this, optionally


accessPackageLocal();


//or


this
.accessPackageLocal();


}

}

Although the child class can access protected
methods from the parent class, any other class
using the child class cannot call them. Let’s
look at an example:

package

com.javaclass.basic;


public class

Employee8SubClassTester {


public

Employee8SubClassTester() {


}


public static void

main(String[] args) {


Employee8SubClass

emp =


new

Employee8SubClass
(
"Fahmin"
);


//of course, you can access a public method in any class


emp.printData();


//You cannot access a protected method


//outside the package


//Only the class subclassing it can access


//protected method of parent


//emp.setData("Nishat");


//however, you can call a protected method in the


//same package


emp.setParentData(
"Nishat"
);



//you can access any methods that is package local


//from within the same package, not from


//outside that package


//String name = emp.getEmpName();



//you cannot access a private method in another class


//String name = emp.empName;


}

}

Run
Employee8SubClassTester.bat

OO Basics

32

Package: import vs fully
-
qualified name

When you use classes from another package, you can use it in two
different ways.


You can import it, then use it directly by class name. When you import,
you can specify to import everything from a package (using *) instead of
specifying multiple classes from the same package.


If it is just a few classes, you should name them individually for clarity
and maintenance purposes.


No matter which approach you take, the compiler will not import every
file from a package even if you specify with a * wildcard. The compiler
will only the classes that are referenced in your program.

OO Basics

33

Package: import vs fully
-
qualified name

Let’s look at an example where we import the Date class from the
java.util package before using it:

package

com.javaclass.utils;


import

java.util.*;

//or

import

java.util.Date;


public class

DateTester1 {



private

Date

d =
new

Date
();
//current system date



public

DateTester1() {


}



public

Date

getSystemDate() {


return

d;


}

}

OO Basics

34

Package: import vs fully
-
qualified name

Now, let’s look at another way of using classes from another package
without actually importing them. Here, we will name the class with
their package name (fully
-
qualified class name):

package

com.javaclass.utils;


public class

DateTester2 {



private

java.util.Date
d =
new

java.util.Date
();
//current system date



public

DateTester2() {


}



public

java.util.Date
getSystemDate() {


return

d;


}

}

OO Basics

35

Package: import vs fully
-
qualified name

Sometimes, you have to fully qualify the class name with its package
when there is a naming conflict.


For example, Date class is defined both in the java.util and java.sql
package (there are many other examples like this).


If you import both of the packages, your class will not compile.


The compiler will complain that the use of Date is ambiguous since it is
found in both classes.

OO Basics

36

Package: import vs fully
-
qualified name

package

com.javaclass.utils;


import

java.util.*;

import

java.sql.*;


public class

DateTester3 {



//now you are bound to define date using fully qualified package name


//private Date d = new Date();


private

java.util.Date
d =
new

java.util.Date
();


private

java.sql.Date
d2 =
new

java.sql.Date
()



public

DateTester3() {


}



//you cannot define it like the following line


//public Date getSystemDate() {


public

java.util.Date
getSystemDate() {


return

d;


}

}

OO Basics

37

Variables: options

The member variables we declare can have different state (like access
levels: private, public, protected & package local). Let’s look at graph
borrowed from the Java Tutorial:

The only required elements of a method declaration are the method's
name, its return type, and a pair of parentheses ( ). You can optionally
provide lists of parameters with proper type. Let’s look at another graph
borrowed from the Java Tutorial:

OO Basics

38

Variables: options

Example:


private static void

convertTestData(
String

number)
throws

Exception

{


//……


}

OO Basics

39

JavaBean, Serialization, transient


In this section, we will introduce the concept of JavaBean.


When you create reusable software components, you usually create a
JavaBean.


Please note JavaBeans are completely different than Enterprise
JavaBeans (EJB). In EJB, you create enterprise services using J2EE (Java
2 Enterprise Edition) and it runs within the context of a J2EE
Application Server like WebLogic, WebSphere, JRun, iPlanet, etc.


A JavaBean is nothing more than a Java class where all of the data
members are private (implementation is hidden) and the access is given
using a set of setter and getter methods.

OO Basics

40

JavaBean, Serialization, transient

Most of your Java program actually would be very close to a JavaBean
except for the fact that your class must implement the Serializable
interface found in Java.io package.


Also, you have to be strict about naming of the setter and getter
methods. If you have a variable called employee, your setter method
must be setEmployee(), and the getter method must be called
getEmployee().


You can use BDK (Bean Development Kit) from Sun to play with
graphically creating JavaBeans.


IDE like JBuilder can generate a lot of code for you when you create a
JavaBean. The JavaBeans Activation Framework is the authoritative
document on how to create and activate JavaBeans.

OO Basics

41

JavaBean, Serialization, transient

package

com.javaclass.utils;


import

java.io.Serializable;


public class
TestBean
implements

Serializable {



private

String user = "HmkUser";


private

transient

String

password =
null
;



public

TestBean() {


}



public

String

getUser() {


return user;


}



public void
setUser(String newUser) {


user = newUser;


}



public void
setPassword(String newPassword) {


user = newPassword;


}




public

String

getPassword() {


return null
;


//we do not want to return the password


//or you can simply not provide a getter method for password


}

}

OO Basics

42

Garbage Collection

Some language requires programmer to explicitly destroy unused
object to free up memory.


C++ is an example. If you are not careful, you can introduce memory
leaks and serious performance bottleneck.


In Java, garbage is collected automatically after the objects get out of
scope. The timing depends on the VM and its priority tasks.


So, your unused objects still might exist for quite some time. You can
call the following method to free up memory although its execution is
not guaranteed:

System
.gc();

OO Basics

43

Factory Methods

Factory methods are convenient static methods that are provided to
make it easier for the users to use a class.


For example, the NumberFormat class provides different instances of
the class through direct calls to different static factory methods.

package

com.javaclass.advanced;


public class

FactoryTester {


public

FactoryTester() {


System
.out.println(
"Class instantiated..."
);


}



public static

FactoryTester getInstance() {


return

new

FactoryTester();


}

}

OO Basics

44

Factory Methods

Now, instead of creating the class the following way:

FactoryTester

tester =
new

FactoryTester
();

We can call the class directly to get the instance by calling the static
factory method getInstance():

FactoryTester

tester =
FactoryTester
.getInstance();

OO Basics

45

String Manipulation

Since Java Strings are objects, you cannot compare one string to
another. For example:

String

myName =
“Shah”
;

String

myName2 =
“Shah”
;

The variables myName and myName2 are not equal. You can, however,
compare if both of them contains the same value with using the equals()
and equalsIgnoreCase() method build
-
in in the String class:

if
(myName.equals(myName2)

System
.out.println(
“Both equal”
);


//if the compare is case insensitive, use the following

if
(myName.equalsIgnoreCase(myName2)

System
.out.println(
“Both equal no case test”
);

OO Basics

46

String Manipulation

The following are some common methods found in the String class.
This method takes different arguments. We will not cover all of them.

//+ operator

//Since Strings are immutable, when you add one string to another, it creates a new string

String

hello =
“Hello”
;

String

world =
“World”
;

String

greet = hello +
“ “

+ world
; //now greet contains “Hello World”, but it is a new String


String

myName =
“Shah”
;

//to find the length of a string, use the length() method:

int

length = myName.length();
//should be 4


//find a value in the string at a specific location (index is 0 based, so last character is length


1 )

//find the first character

char

first = myName.charAt(
0
);
//should return S

//find the last character

char

last = myName.charAt(length


1
);
//should return h


//extract part of the string

//following example taken from the Java Tutorial:

String

anotherPalindrome =
“Niagara. O roar again!”
;

String

roar = anotherPalindrome.substring(
11
,
15
);
//roar should contain “roar”

OO Basics

47

String Manipulation

Here is the graphic view of a String value (courtesy: The Java Tutorial):

//extract part of the string

//following example taken from the Java Tutorial:

String

anotherPalindrome =
“Niagara. O roar again!”
;

String

roar = anotherPalindrome.substring(
11
,
15
);
//roar should contain “roar”

OO Basics

48

String Manipulation

Here are some more String methods:

//String accessors

//searching for specific characters

String

accountNumber =
“A2098B98A2”
;

//suppose we want to separate this string with index starting with A

//and before the last A, and part starting from last A to end of the string

int

startPos = accountNumber.indexOf(
‘A’
); //returns 0

int

endPos = accountNumber.lastIndexOf(‘
A’
); //returns 8

//now, we can pick up the tokens

String

acctNumberStart = accountNumber.substring(startPos, endPos);
//returns A2098B98

String

acctNumberFinish = accountNumber.substring(endPos, accountNumber.length());
//returns A2



//startsWith, endsWith

String

employeeNumber=
”E234
-
098
-
0987
-
Z”
;

//for example, we want to pick up all employees staring with E and ending with Z

boolean

starsNumber = employeeNumber.startsWith(
“E”
); //returns true

boolean

endsWith = employeeNumber.endsWith(
“Z”
);//returns true


//toUpper, toLower

String

namePassed =
“ joHn “
;

//for example, you want to convert user input to UPPERCASE

namePassed = namePassed.toUpperCase();
//value: JOHN

//to make lowercase

namePassed = namePassed.toLowerCase();
//john


//trim()

//user may input spaces at the beginning or end, we can trim them

namePassed = namePassed.trim();
//john

OO Basics

49

Date Manipulation

You can display date in different format based on your locale. The
SimpleDateFormat class provides some handy methods.

//import java.text.*;

//import java.util.*;

Date

today = new
Date
();
//picks up System date

SimpleDateFormat

dateInstance =
new

SimpleDateFormat
(
("MM'/'dd'/'yyyy"
);

dateStr = dateInstance.format(date);
//output: 08/16/2002


You can also receive date as String from the user and format it using
the SimpleDateFormat class:

//import java.text.*;

//import java.util.*;

String

dateStr=
"10/19/2001"
;//output: 10/19/2001

dateStr="10/19/01";
//output:10
-
19
-
01

//your dateStr must come in as defined here, year could be 2 or four digit

SimpleDateFormat

instance = new
SimpleDateFormat
(
"MM'/'dd'/'yy"
);

try {

Date

dt = instance.parse(dateStr);

}

catch (
ParseException

ex) {

//value passed in not suitable for creating date

}

OO Basics

50

Date Manipulation

You can also manipulate time from the Date object:

//import java.text.*;

//import java.util.*;


Date

today =
new

Date
();


DateFormat

formatter =
DateFormat
.getTimeInstance(
DateFormat
.DEFAULT);

String

defaultTime = formatter.format(today);
//output: 9:14:41 AM


DateFormat

formatter =
DateFormat
.getTimeInstance(
DateFormat
.LONG);

String longTime = formatter.format(today);
//output: 9:14:41 AM CDT


DateFormat

formatter =
DateFormat
.getTimeInstance(
DateFormat
.FULL);

String fullTime = formatter.format(today);
//output: 9:14:41 AM CDT


DateFormat

formatter =
DateFormat
.getTimeInstance(
DateFormat
.MEDIUM);

String mediumTime = formatter.format(today);
//output: 9:14:41 AM


DateFormat

formatter =
DateFormat
.getTimeInstance(
DateFormat
.SHORT);

String

shortTime = formatter.format(today);
//output: 9:14 AM

OO Basics

51

Date: GregorianCalendar

Date can be manipulated using the implementation of the Calendar
class found in java.util package.


One of the utility classes that implement the Calendar class is the
GregorianCalendar class that also can be found in the java.util
package.


Do not use the deprecated methods in the Date class to manipulate
date.

OO Basics

52

Date: GregorianCalendar

//import java.text.*;

//import java.util.*;


GregorianCalendar

calender;

calender =
new

GregorianCalendar
();
//will use system date


//another overloaded constructor: year, month, day, hour, minutes

calender =
new

GregorianCalendar
(
2002
,
7
,
22
,
12
,
20
);



//another overloaded constructor: year, month, day, hour, minutes, seconds

calender =
new

GregorianCalendar(
2002
,
7
,
22
,
12
,
20
,
10
);


//you can use the overloaded constructor to pass a date to initialize

//month is zero
-
based, 0=January, and 11=December

calender =
new

GregorianCalendar
(
2002
,
7
,
22
);

Date

today = calender.getTime();
//will return date from the Calendar


GregorianCalendar

calender2 =
new


GregorianCalendar

(
2002
,
7
,
22
,
12
,
20
,
10
);

if
(calender.equals(calender2)) {


System
.out.println(
"Both date are equal..."
);

}

OO Basics

53

Date: GregorianCalendar

Other notable methods (most of them are overloaded)


before()


after()


get()


set()


add()


setTime()

OO Basics

54

Discussion

Homework


Questions


Misc.