04-Classes.v2.0.0

Download Report

Transcript 04-Classes.v2.0.0

www.espirity.com
Classes
Dwight Deugo ([email protected])
Nesa Matic ([email protected])
Additional Contributors

None as of September, 2004
2
© 2003-2004, Espirity Inc.
Module Overview
1.
2.
3.
4.
Classes in Java
Static fields and methods
Commonly used classes in Java
Searching Java classes in Eclipse
3
© 2003-2004, Espirity Inc.
Module Road Map
1. Classes in Java






2.
3.
4.
What are classes?
Defining classes
.java files
Packages and access level
.jar files and classpath
Fields, methods, and constructors
Static fields and methods
Commonly used classes in Java
Searching Java classes in Eclipse
4
© 2003-2004, Espirity Inc.
What is a Class?




A class defines an object by defining its state
and behavior
A class is also collection of objects that
encapsulate similar data and behavior
Classes are used for creating new objects
Classes define objects type
5
© 2003-2004, Espirity Inc.
How to Define Java Class?

Java class is defined with using class
keyword

Class name follows the keyword, and by
convention starts with capital letter


For example Policy, Client, House, etc.
Class access level must be specified before
the class keyword
public class Policy{
…
}
6
© 2003-2004, Espirity Inc.
Class Modifiers


Class Modifies identifies visibility of the class
There are two access modifiers for a class:

public


Identifies that any other class can reference defined
class
Not specified


Identifies that only classes defined in the same
package can reference defined class
It is default access level modifier
7
© 2003-2004, Espirity Inc.
.java Files

Java classes are contained in .java files



One file can contain one public class
One file can contain more than one non-public
classes
The file name is the same as the class name
contained in the file
package com.espirity.demo.models;
public class Policy{
…
}
8
Policy.java
© 2003-2004, Espirity Inc.
Package

Package groups related classes



Classes are usually related by their functionality,
for example domain classes, testing classes, etc.
Package is identified using package keyword
Package is unique identifier for a class


Two classes with a same name cannot be in the
same package
Different packages can contain same class
names
package com.espirity.demo.models;
9
© 2003-2004, Espirity Inc.
Referencing Classes


A class must be fully referenced every time
when used outside of its package
Full qualifier for a class is used

package name + class name
package com.espirity.demo.tests;
public class PolicyTester{
com.espirity.demo.models.Policy policy;
…
policy = new com.espirity.demo.models.Policy();
}
10
© 2003-2004, Espirity Inc.
Import Statement

Used to identify which classes can be
referenced without fully identifying them


Specified with import keyword
Can specify a class, or all classes from a package
package com.espirity.demo.tests;
import com.espirity.demo.models.Policy;
public class PolicyTester{
Policy policy;
…
policy = new Policy();
}
11
© 2003-2004, Espirity Inc.
Ambiguities in Importing Classes


Happens when same class is imported from
different packages
Compiling error states that there is
ambiguity is using the class

Explicit reference to the class must be made
package com.espirity.demo.tests;
import com.espirity.demo.models.*;
import com.insurancecompany.policyapp.models.*;
public class PolicyTester{
Policy policy;
…
policy = new Policy();
}
12
Ambiguity in type Policy
© 2003-2004, Espirity Inc.
Compiling Classes



When writing Java class, the source code is
stored in .java files
When compiling Java classes, compiled code
is stored in .class files
Compiled Java classes from the same
package are compiled into the same
directory

The directory name matched package name
13
© 2003-2004, Espirity Inc.
Classpath and .jar files

Classpath allows Java Virtual Machine to find
the code

CLASSPATH environment variable is used to
indicate the root of where packages are


Packages are subdirectories under the root
Compiled Java classes can be packaged and
distributed in Java Archive (.jar) files

Packages in the .jar file are replaced with
directories
14
© 2003-2004, Espirity Inc.
What are Fields?


Object state is implemented through fields
Fields are defined at the class level



All instances of the same class have the same
fields
Fields values can be different from instance to
instance
Fields are also knows as instance variables
Policy
client
premium
policyNumber
15
© 2003-2004, Espirity Inc.
Defining Fields

A field definition consists of:



Access modifier
Field type
Field name
package com.espirity.demo.models;
public class Policy {
private Client client;
private String policyNumber;
private double premium;
}
16
© 2003-2004, Espirity Inc.
Initializing Fields


Fields are initialized when new instance of a
class is created
Primitive type fields get a default value




Numeric primitives are initialized to 0 or 0.0
boolean primitives are initialized to false
Reference type fields are initialized to null as
they do not yet reference any object
Fields can also be explicitly initialized when
declared
17
© 2003-2004, Espirity Inc.
Initializing Fields Explicitly


Possible when declaring fields
Not commonly used

Constructors are generally used for initializing
fields
package com.espirity.demo.models;
public class Policy {
private Client client = new Client();
private String policyNumber = "PN123";
private double premium = 1200.00;
}
18
© 2003-2004, Espirity Inc.
Field Access Modifier

There are four different modifiers:

public


protected


Allows direct access to fields from within the package where
class is defined
default


Allows direct access to fields from outside the package where
class is defined
Allows direct access to fields from within the package where
class is defined and all subclasses of the class
private

Allows direct access to fields from class only
19
© 2003-2004, Espirity Inc.
What are Methods?

Methods represent behavior of an object


All instances of the same class have same
methods defined and understand same
messages
When a message is sent to an object,
method that corresponds to that message is
executed

Methods represent implementation of messages
20
© 2003-2004, Espirity Inc.
Methods and Encapsulation

To allow access to private
fields, getter and setter
methods are commonly used



Getters return fields values
Setters set fields values to
passed parameters
Getters and setters enforce
encapsulation
21
Policy
client
premium
policyNumber
getClient
getPremium
getPolicyNumber
setClient
setPremium
setPolicyNumber
© 2003-2004, Espirity Inc.
Defining Methods

Methods are defined with:




Access modifier, same as for fields
Return type
Method name
Parameters, identified with type and name
package com.espirity.demo.models;
public class Policy {
…
public void setClient(Client aClient){
…
}
}
22
© 2003-2004, Espirity Inc.
Constructors

Special methods used for creating instances
of a class:



access modifier
same name as the class
manipulate new instance
package com.espirity.demo.models;
public class Policy {
…
public Policy(){
setClient(new Client());
setPolicyNumber("PN123");
setPremium(1200.00);
}
}
23
© 2003-2004, Espirity Inc.
Using Constructors

Use new before class name to create an
instance of a class
package com.espirity.demo.models;
public class Policy {
…
public Policy(Client aClient, String policyNumber, double premium){
setClient(aClient);
setPolicyNumber(policyNumber);
setPremium(premium);
}
}
Policy policy = new Policy(new Client(), "PN123", 1200.00);
24
© 2003-2004, Espirity Inc.
Policy Class Implementation
package com.espirity.demo.models;
public class Policy {
private Client client;
private String policyNumber;
private double premium;
public Policy(Client aClient, String policyNumber, double premium){
setClient(aClient);
setPolicyNumber(policyNumber);
setPremium(premium);
}
public Client getClient() {
return client;
}
public String getPolicyNumber() {
return policyNumber;
}
public double getPremium() {
return premium;
}
public void setClient(Client aClient) {
this.client = aClient;
}
public void setPolicyNumber(String policyNumber) {
policyNumber = policyNumber;
}
public void setPremium(double premium) {
premium = premium;
}
}
25
© 2003-2004, Espirity Inc.
Module Road Map
1.
Classes in Java
2. Static fields and methods



3.
4.
Defining and using static fields
Defining and using static methods
Singleton pattern
Commonly used classes in Java
Searching Java classes in Eclipse
26
© 2003-2004, Espirity Inc.
What are Static Fields?

Static fields represent data shared across all
instances of a class




There is only one copy of the field for the class
Modification to the static field affects all
instances of the class
Static fields are also knows as class variables
Some of the static fields usages include:


Constants
Implementation of singleton pattern
27
© 2003-2004, Espirity Inc.
Declaring Static Fields


Declared by using the static keyword
Java constants are declared as static final
fields

Modifier final indicates that field value cannot be
changed
public class Count{
public static String INFO = "Sample Count Class";
public final static int ONE = 1;
public final static int TWO = 2;
public final static int THREE = 3;
}
28
© 2003-2004, Espirity Inc.
Accessing Static Fields

Static field can be accessed:

Directly
Console
System.out.println(Count.ONE);

1
Indirectly

Cannot access final fields directly
Count count = new Count();
System.out.println(count.INFO);
29
Console
Sample Count Class
© 2003-2004, Espirity Inc.
Static Methods

Define behavior related to the class, not
individual instances


Defined by using the static keyword
Commonly used for accessing static fields

Getter and setter methods
public class Count{
private static String INFO = "Sample Count Class";
public final static int ONE = 1;
public final static int TWO = 2;
public final static int THREE = 3;
public static String getInfo(){
return INFO;
}
}
30
© 2003-2004, Espirity Inc.
Using Static Methods

Static methods can be also accessed by
instance or class
Console
Sample Count Class
System.out.println(Count.getInfo());
Console
Count count = new Count();
System.out.println(count.getInfo());
31
Sample Count Class
© 2003-2004, Espirity Inc.
Singleton Pattern

Ensures existence of only one instance of a
class

This instance is usually stored in the static field
and accessed through a static method
public class Singleton {
private static Singleton theInstance;
public static Singleton getInstance(){
if (theInstance == null){
theInstance = new Singleton();
}
return theInstance;
}
private Singleton(){
super();
}
}
32
© 2003-2004, Espirity Inc.
Using Singleton Pattern

Call on creation of new instance will fail
new Singleton()

error
The constructor Singleton() is not visible
Calling the static method will return the
instance
Singleton.getInstance()
Returns only instance of the class
33
© 2003-2004, Espirity Inc.
Module Road Map
1.
2.
Classes in Java
Static fields and methods
3. Commonly used classes in Java



4.
Object class
String and String Buffer classes
Class and System classes
Searching Java classes in Eclipse
34
© 2003-2004, Espirity Inc.
Package java.lang



It is a core package in Java
When classes from this package are
referenced there is no need for import
statement
Contains core set of classes such as:





Object
String
StringBuffer
System
Class
35
© 2003-2004, Espirity Inc.
Object Class

Object class is the top of the class hierarchy in Java



Every class inherits from Object class
Defines some default behavior that is mainly overridden
in subclasses
Commonly overridden methods from Object class
are:




toString()
equals()
hashCode()
clone()
36
© 2003-2004, Espirity Inc.
Method equals()

Meant to return whether or not two objects
are equal

Default implementation in Object class returns
whether or not are objects identical


The == operator is used
Overriding method allows to change the equality
criteria

For example two policies are the same if they have
the same client, same policyNumber and same
premium
37
© 2003-2004, Espirity Inc.
Example equals() method

An example of overriding the equals()
method in the Policy class

Two policies are equal if their policy numbers are
equal
public boolean equals(Object anObject){
if ((anObject == null)||(anObject.getClass() != this.getClass()))
return false;
Policy policy = (Policy)anObject;
return getPolicyNumber().equals(policy.getPolicyNumber());
}
38
© 2003-2004, Espirity Inc.
Method hashCode()

Used by collections, primarily HashMap and
HashSet



Returns an int for indexing
Hash codes must be identical for objects that are
equal
For the Policy class implementation of the hash
code method could be:
public int hashCode(){
return getPolicyNumber().hashCode();
}
39
© 2003-2004, Espirity Inc.
Method clone()


Used to obtain copy of an object
The default implementation of the clone()
method in Object class does shallow copy

New instance of the class is created, but all
containing fields are the same
policy
Policy policy;
policy = new Policy();
Policy policyCopy;
policyCopy = policy.clone();
client
policy
Number
policyCopy
premium
40
© 2003-2004, Espirity Inc.
Cloning Rules

Classes must implement Cloneable interface
to allow their instances to be cloned



CloneNotSupported exception thrown if objects
cannot be cloned
In our example, both Client and Policy classes
must implement Cloneable interface to support
cloning
Method clone() is protected in Object class

Usually made public when overridden to allow
use everywhere
41
© 2003-2004, Espirity Inc.
String Class


Used for manipulating constant set of
characters
Literals are String instances that cannot be
changed, and have fixed size
String greeting = "Hello" + ", do you like my hat?";
//"Hello, do you like my hat?"
String hello = greeting.substring(0,5);
//"Hello"
String upercase = hello.toUpperCase();
//"HELLO THERE!"
boolean isEqual = hello.equals("HELLO");
//false
boolean isEqual1 = hello.equalsIgnoreCase("HELLO"); //true
42
© 2003-2004, Espirity Inc.
StringBuffer Class


Used for strings that can change
Allows for adding, replacing and deleting
characters


When characters are added size increases
StringBuffer object knows about its length and
capacity


length indicates how many characters it has
capacity indicates how many characters it can
currently hold
43
© 2003-2004, Espirity Inc.
Using StringBuffer Class

Typical buffer manipulation includes
appending, replacing, inserting and deleting
characters
StringBuffer buffer = new StringBuffer();
buffer.append("Hello");
buffer.append(", do you");
buffer.insert(13, " like my hat?");
System.out.println(buffer);
buffer.replace(0,5,"Hi");
System.out.println(buffer);
buffer.delete(2,buffer.length()-1);
buffer.replace(buffer.length()-1,
buffer.length(), "!");
System.out.println(buffer);
44
Console
Hello, do you like my hat?
Hi, do you like my hat?
Hi!
© 2003-2004, Espirity Inc.
Class Class

Java classes are not objects themselves


They are templates for data and behavior and
also factory for creating instances
Instances of Class class represent Java
classes runtime

They allow developers to find runtime
information about the class
45
© 2003-2004, Espirity Inc.
Class Protocol

Allows for queering the class

Finding methods, fields and more
HomePolicy policy = new HomePolicy(1200);
Class policyClass = policy.getClass();
//class HomePolicy
policyClass.getDeclaredFields();
//[private House HomePolicy.house]
Class policySuperclass = policyClass.getSuperclass();
//class Policy
policySuperclass.getName();
//Policy
46
© 2003-2004, Espirity Inc.
System Class

Provides an access to system functions
through its static protocols


It is not possible to create instances of System
class
Defines static methods and fields
System.out.println("Hello, do you like my hat?");
Hello, do you like my hat?
Console
47
© 2003-2004, Espirity Inc.
Module Road Map
1.
2.
3.
Classes in Java
Static fields and methods
Commonly used classes in Java
4. Searching Java classes in Eclipse



Search use
Search view
Result view
48
© 2003-2004, Espirity Inc.
Searching in Eclipse

It is impossible to know entire Java library


It allows for searching on:






Eclipse helps with its extensive built-in search
mechanism
Classes
Methods
Constructor
Field
Package
It allows searching for:


Declarations
References
49
© 2003-2004, Espirity Inc.
Search View

Opens by choosing Search from the pull-down
menu
50
© 2003-2004, Espirity Inc.
Search Result View


Contains results of performed search
Double-click on the item in the result view opens
requested Java type
51
© 2003-2004, Espirity Inc.
Review

In this module we discussed:



Java classes, packages, fields and methods
Access level
Static fields, and methods



Singleton pattern
Commonly used classes in Java
Searching for Java classes in Eclipse
52
© 2003-2004, Espirity Inc.