classes dwight deugo ([email protected]) nesa matic ([email protected])

52
Classes Classes Dwight Deugo ([email protected]) Dwight Deugo ([email protected]) Nesa Matic ([email protected]) Nesa Matic ([email protected]) www.espirity.com

Upload: raymond-lambert

Post on 18-Jan-2016

247 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

ClassesClasses

Dwight Deugo ([email protected])Dwight Deugo ([email protected])Nesa Matic ([email protected])Nesa Matic ([email protected])

www.espirity.com

Page 2: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

2 © 2003-2004, Espirity Inc.

Additional Contributors

None as of September, 2004

Page 3: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

3 © 2003-2004, Espirity Inc.

Module Overview

1. Classes in Java2. Static fields and methods3. Commonly used classes in Java4. Searching Java classes in Eclipse

Page 4: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

4 © 2003-2004, Espirity Inc.

Module Road Map

1. Classes in Java What are classes? Defining classes .java files Packages and access level .jar files and classpath Fields, methods, and constructors

2. Static fields and methods3. Commonly used classes in Java4. Searching Java classes in Eclipse

Page 5: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

5 © 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

Page 6: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

6 © 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{…

}

Page 7: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

7 © 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

Page 8: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

8 © 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{…

}Policy.java

Page 9: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

9 © 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;

Page 10: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

10 © 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();

}

Page 11: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

11 © 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

packagepackage com.espirity.demo.tests;import com.espirity.demo.models.Policy;

public class PolicyTester{Policy policy;…policy = new Policy();

}

Page 12: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

12 © 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

madepackage com.espirity.demo.tests;import com.espirity.demo.models.*;import com.insurancecompany.policyapp.models.*;

public class PolicyTester{Policy policy;…policy = new Policy();

}

Ambiguity in type Policy

Page 13: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

13 © 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

Page 14: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

14 © 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

Page 15: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

15 © 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

clientpremiumpolicyNumber

Page 16: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

16 © 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;

}

Page 17: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

17 © 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

Page 18: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

18 © 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;

}

Page 19: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

19 © 2003-2004, Espirity Inc.

Field Access Modifier

There are four different modifiers: public

Allows direct access to fields from outside the package where class is defined

protected Allows direct access to fields from within the package

where class is defined default

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

Page 20: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

20 © 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

Page 21: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

21 © 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

Policyclient

premiumpolicyNumber

getClientgetPremiumgetPolicyNumbersetClientsetPremiumsetPolicyNumber

Page 22: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

22 © 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

namepackage com.espirity.demo.models;

public class Policy {…public void setClient(Client aClient){…}

}

Page 23: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

23 © 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);

}}

Page 24: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

24 © 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);

Page 25: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

25 © 2003-2004, Espirity Inc.

Policy Class Implementationpackage 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;}

}

Page 26: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

26 © 2003-2004, Espirity Inc.

Module Road Map

1. Classes in Java

2. Static fields and methods Defining and using static fields Defining and using static methods Singleton pattern

3. Commonly used classes in Java4. Searching Java classes in Eclipse

Page 27: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

27 © 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

Page 28: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

28 © 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;

}

Page 29: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

29 © 2003-2004, Espirity Inc.

Accessing Static Fields

Static field can be accessed: Directly

Indirectly Cannot access final fields directly

System.out.println(Count.ONE);

Count count = new Count();System.out.println(count.INFO);

1Console

Sample Count ClassConsole

Page 30: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

30 © 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;}

}

Page 31: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

31 © 2003-2004, Espirity Inc.

Using Static Methods

Static methods can be also accessed by instance or class

Count count = new Count();System.out.println(count.getInfo());

Sample Count ClassConsole

System.out.println(Count.getInfo());Sample Count Class

Console

Page 32: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

32 © 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 methodpublic class Singleton {

private static Singleton theInstance;public static Singleton getInstance(){

if (theInstance == null){theInstance = new

Singleton();}return theInstance;

}private Singleton(){

super();}

}

Page 33: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

33 © 2003-2004, Espirity Inc.

Using Singleton Pattern

Call on creation of new instance will fail

Calling the static method will return the instance

new Singleton() The constructor Singleton() is not visibleerror

Singleton.getInstance() Returns only instance of the class

Page 34: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

34 © 2003-2004, Espirity Inc.

Module Road Map

1. Classes in Java2. Static fields and methods

3. Commonly used classes in Java Object class String and String Buffer classes Class and System classes

4. Searching Java classes in Eclipse

Page 35: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

35 © 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

Page 36: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

36 © 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()

Page 37: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

37 © 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

Page 38: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

38 © 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());

}

Page 39: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

39 © 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();

}

Page 40: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

40 © 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 samePolicy policy;policy = new Policy();Policy policyCopy;policyCopy = policy.clone();

policy

policyCopy

client

policyNumber

premium

Page 41: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

41 © 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

Page 42: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

42 © 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"); //falseboolean isEqual1 = hello.equalsIgnoreCase("HELLO"); //true

Page 43: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

43 © 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

Page 44: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

44 © 2003-2004, Espirity Inc.

Using StringBuffer Class

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);

Hello, do you like my hat?

Console

Hi, do you like my hat?

Typical buffer manipulation includes appending, replacing, inserting and deleting characters

Hi!

Page 45: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

45 © 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

Page 46: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

46 © 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 HomePolicypolicyClass.getDeclaredFields();

//[private House HomePolicy.house]Class policySuperclass = policyClass.getSuperclass();

//class PolicypolicySuperclass.getName();

//Policy

Page 47: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

47 © 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

Page 48: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

48 © 2003-2004, Espirity Inc.

Module Road Map

1. Classes in Java2. Static fields and methods3. Commonly used classes in Java

4. Searching Java classes in Eclipse Search use Search view Result view

Page 49: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

49 © 2003-2004, Espirity Inc.

Searching in Eclipse It is impossible to know entire Java library

Eclipse helps with its extensive built-in search mechanism

It allows for searching on: Classes Methods Constructor Field Package

It allows searching for: Declarations References

Page 50: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

50 © 2003-2004, Espirity Inc.

Search View

Opens by choosing Search from the pull-down menu

Page 51: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

51 © 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

Page 52: Classes Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com)

52 © 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