Object Oriented Development

214
Object Oriented Object Oriented Development Development Java

description

Object Oriented Development. Java. Objectives. Develop a basic understanding of: OO Concepts Networking Web servers Servlets (live reports from databases) Using an IDE to develop applications. Learn enough Java to enable you to continue learning on your own. Non-objectives. - PowerPoint PPT Presentation

Transcript of Object Oriented Development

Page 1: Object Oriented Development

Object Oriented DevelopmentObject Oriented DevelopmentJava

Page 2: Object Oriented Development

ObjectivesObjectivesDevelop a basic understanding of:OO ConceptsNetworkingWeb serversServlets (live reports from databases)Using an IDE to develop applications.Learn enough Java to enable you to

continue learning on your own.

Page 3: Object Oriented Development

Non-objectivesNon-objectivesLanguage theory.Thorough tour of the Java API

Application Programmer InterfaceDiscussion of inner-workings of Java.GUI application development

(Swing/AWT)Why the designers of Java did what they

did.

Page 4: Object Oriented Development

PrerequisitesPrerequisitesClasses assume basic knowledge of:AlgorithmsNetworksWorld Wide WebDatabases

Page 5: Object Oriented Development

Class FormatClass Format1. Lectures.2. Review Questions.3. Lab work.All lab work is limited to the

illustrating the subject material presented. Lab work algorithms are simple.

Ask questions.

Page 6: Object Oriented Development

Object Oriented DevelopmentObject Oriented Development

Page 7: Object Oriented Development

Other MethodologiesOther Methodologies

For example:– Procedural– Aspect Oriented Programming– Integration Oriented Programming– etc…

Page 8: Object Oriented Development

Introduction Introduction

First primitive Object Oriented Programming (OOP) language, Simula, released in 1967

Some think it simplifies coding as opposed to Procedural, or Aspect Oriented Programming.

Coded from the point of view of items in a problem rather than a set of procedures.

Office Example.

Page 9: Object Oriented Development

Object Oriented ProgrammingObject Oriented Programming

A PIE– Abstraction– Polymorphism– Inheritance– Encapsulation

Page 10: Object Oriented Development

AbstractionAbstraction

Representing the essential parts of a real-world thing as data.

What’s needed for your solution.Some abstractions of a Car

– VIN, Color, Make, Model, Year (Manufacturer)

– Transponder ID, License Plate Number, Account Number (Fast Lane)

Page 11: Object Oriented Development

EncapsulationEncapsulation

Binding data together with its functionality (methods)

– Department.addEmployee()– Car.drive()– Door.open()– File.open()

Page 12: Object Oriented Development

InheritanceInheritance

Building on an existing concept by adding new properties or functionality.

Fruit– grams– calories per gram

Citrus is a Fruit– can be squeezed into juice

“Is A” implies inheritance

Page 13: Object Oriented Development

PolymorphismPolymorphism

Scary name; simple concept.Literally: “Many shapes”

Overloading– Traditionally we have

square(int), squareF(float)…– In OO we have square(int), square(float) …

Overriding– Same function as parent class being

respecified in child class.

Page 14: Object Oriented Development

ExampleExample

Carint speeddrive()

drive(int speed)

SportsCardrive()

overdrive()

1. Sports Car inherits from car

2. Drive method is overriden as well as overloaded.

3. Car and SportsCar abstract the “concept” of a car.

4. Car and SportsCar encapsulate the functionality of a car.

Page 15: Object Oriented Development

Classes and ObjectsClasses and Objects

A Class is a collection of properties (also called fields or member variables) and methods that define a new data type

An Object is an instance of a class.

Example– If Person is a class– Bob, Jim, and Mary are all objects (instances

of the Person Class)

Page 16: Object Oriented Development

JAVAJAVAObject Based from the Start

Page 17: Object Oriented Development

What is Java?What is Java?

The Java LanguageJava Virtual MachineJava API

Page 18: Object Oriented Development

The Java LanguageThe Java Language

Developed at Sun Microsystems in 1991, released to the public in 1994

Based upon C++, but it was made to be accessible to more programmers.

Object Oriented. Everything is a class (i.e no stand-alone functions)

Delivers secure, portable, multi-threaded, networking related applications

Case-sensitive

Page 19: Object Oriented Development

Java Virtual MachineJava Virtual Machine

Referred to as the Sandbox or JVM Java code compiles into bytecode, unlike

most other languages that compile to machine code.

Since bytecode is readable to the JVM, Java is portable to any operating system that has a Java Virtual Machine built for it.

Page 20: Object Oriented Development

Java APIJava APIApplication Programmer InterfaceApplication Programmer Interface

A collection of software libraries, called packages, that contain Java classes

As testimony to the reusability of Java code, you use the Java API to create functionality.

Use the import keyword to access a software library

Example:import java.io.*;

Page 21: Object Oriented Development

Programming Java ApplicationsProgramming Java ApplicationsA Java application is a collection of

classes with one class that contains a main method as an entry point.

Most classes must reside in a file with the same name e.g. A public class called Learning must reside in

a file called Learning.java Class declarations and control flow structures are

contained in {} Variable declarations, expressions, functions and

library calls end with semi-colons

Page 22: Object Oriented Development

Main MethodMain Method

public static void main(String[] args){ }

Accessible to any class

Class method

No return value

An array of String objects

Method name

Page 23: Object Oriented Development

CommentsComments

Java uses C/C++ commenting styles.Single line comments are denoted by //

int a; // a will be used to count sheep

Block comments begin with /* and end with */ /* Author: Joe Smith

Date: Jan 7th, 2002 Description: First lines of code */

Page 24: Object Oriented Development

public class HelloWorld {public static void main( String[] args){

System.out.println(“Hello World”);}

}Static object

Object contained in System

Method of out object

Declaration of class Entrance point for application

Page 25: Object Oriented Development

Compiling and Running Compiling and Running Java ApplicationsJava ApplicationsTo transform files into bytecode, use the

javac (abbreviated java compile) command javac [filename] java [classname]

Page 26: Object Oriented Development

Review QuestionsReview Questions

1. What is the purpose of the main method?2. What is the difference between a Class and an

Object?3. Given a cookie cutter and cookies, which

would best represent an object, and which best represents a class?

4. What two ways are comments marked in a Java program?

5. How do you include other libraries so that your class can use them?

Page 27: Object Oriented Development

Lab 1Lab 1

Hola.java

public class Hola {public static void main( String args[]){

System.out.println(“Hello World”);}

}

Page 28: Object Oriented Development

Borland’s JBuilderBorland’s JBuilder

An Integrated Development Environment (IDE)

Project– A collection of source files that solve a

problem.

Page 29: Object Oriented Development

Creating a New ProjectCreating a New Project

Page 30: Object Oriented Development

Using the Project WizardUsing the Project Wizard

Page 31: Object Oriented Development

Creating a New ClassCreating a New Class

Page 32: Object Oriented Development

Using the Class WizardUsing the Class Wizard

Page 33: Object Oriented Development

Create Your Class.Create Your Class.

Page 34: Object Oriented Development
Page 35: Object Oriented Development

To Run a ProjectTo Run a ProjectWe have to tell Jbuilder which We have to tell Jbuilder which class has the main method.class has the main method.

Click on the Click on Select HelloWorld

Page 36: Object Oriented Development

Lab 2Lab 2

Hello World in Jbuilder

public class HelloWorld {

public Helloword() { }

public static void main( String args[]){

System.out.println(“Hello World”);}

}

Page 37: Object Oriented Development

Variables and OperatorsVariables and Operators

Primitive Data-typesClasses and ObjectsOperators

Page 38: Object Oriented Development

Primitive Data-typesPrimitive Data-types

A data-type that does not contain any other data-types

List of Primitive Data-types– boolean byte

– int long

– float double

– char short

JVM ensures these types are identical on all platforms

Page 39: Object Oriented Development

Defining VariablesDefining Variables

Format:– datatype variableName;

Examples:int a;boolean done;float salary;

Page 40: Object Oriented Development

Using Identifiers of VariablesUsing Identifiers of Variables

Identifiers are the names of the variables that a programmers assigns.

Identifiers can consist of alphanumeric symbols, underscores and dollar signs, but cannot be reserved operator symbols.

Identifiers may not begin with numeric symbols.

Identifiers are case sensitive.

Page 41: Object Oriented Development

Variable NamesVariable Names

Examples of Valid Identifiers $joe J3_the_robot _this4$ i

Style: stusCar

employeeJohnmyRedRobot

vPawns

Page 42: Object Oriented Development

Classes and ObjectsClasses and Objects

Class– A collection of properties (also called fields or

member variables) and methods that define a new data type

like metadata (like the def. of a db table)Object

– A particular instance of a class. like data (the rows in a database table)

Page 43: Object Oriented Development

ClassClass

A class is a description of what an object will look like and how it will behave.

Classes are like an idea. You cannot use them until you make an object out of the class.

Page 44: Object Oriented Development

Reference Variables & ObjectsReference Variables & ObjectsReference Variables point to objects

datatype refVarWhen they are first defined, they point

nowhere.

Pawn stusPawn;Pawn jeffsPawn;

Page 45: Object Oriented Development

newnew

new reserves memory for an object of a specified class and returns a reference to it.

ClassName myObj;myObj = new Constructor();

Pawn p;p = new Pawn();

Page 46: Object Oriented Development

Constructing ObjectsConstructing ObjectsBecause objects are complex datatypes,

(classes) they need to be “constructed”.Format:

refVar = new [constructor()] ;

Pawn stusPawn;Pawn jeffsPawn;stusPawn = new Pawn();

Page 47: Object Oriented Development

Construction Construction ContinuedContinued

Pawn stusPawn;Pawn jeffsPawn;stusPawn = new Pawn();stusPawn = new Pawn();stusPawn = new Pawn();

Page 48: Object Oriented Development

Garbage CollectionGarbage Collection

Garbage Collection automatically reclaims an object when its reference count is zero

Objects have a reference Count

Page 49: Object Oriented Development

Review QuestionsReview Questions

1. Is int a class or a primitive datatype?

2. When you declare a reference variable, what does it point to? Pawn p;

3. What does the Garbage Collector do?

Page 50: Object Oriented Development

Defining a classDefining a class

Format:

[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter

}

Page 51: Object Oriented Development

PropertiesProperties

Properties are variables that are encapsulated by a class

Class Person {int age;boolean male;float salary;

}

Page 52: Object Oriented Development

Defining a classDefining a class

Format:

[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter

}

Page 53: Object Oriented Development

ConstructorsConstructors

Constructors are special methods called upon the creation of an object

Any initialization of an object should take place in a constructor

If omitted, a default constructor is called setting all values to null.

Always have the same name as the classAlways have the same name as the classAlways have the same name as the class

Page 54: Object Oriented Development

ConstructorConstructorpublic class Pawn{

String color;int xPosition;int yPosition;

public Pawn() {color=“Black”;xPosition=0;yPosition=1;

}}

Somewhere in your code:Pawn x;x = new Pawn();

Page 55: Object Oriented Development

Instantiation of ObjectsInstantiation of ObjectsCreating a working copy of a class (Making

an Object).class Pawn {

String color;int xPosition;int yPosition;

}

Somewhere in your code:Pawn stusPawn;

stusPawn = new Pawn();

Shortcut:[datatype] [refVar] = new [constructor()]

Pawn stusPawn = new Pawn();

Page 56: Object Oriented Development

Using Multiple ConstructorsUsing Multiple Constructors

Page 57: Object Oriented Development

Format of a classFormat of a class

[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter

}

Page 58: Object Oriented Development

MethodsMethods

Methods are functions encapsulated by the class.

jeffsCar.drive();mikesOven.setTemperature(350);

Methods can have any number of parameters including zero.

Methods may return one or no variables.

mikesOven.setTemperature(350);int y;y = mikesOven.getTemperature();

Page 59: Object Oriented Development

Coding A MethodCoding A Method

visibility return-type name(parameters) {do stuff

}

public float getDegrees() {float d;d = (9/5)*celsius+32;return d;

}

Page 60: Object Oriented Development
Page 61: Object Oriented Development
Page 62: Object Oriented Development

voidvoid Methods Methods

Methods don’t always have to return something.

Use the return type of void when you do not want to return anything.

Page 63: Object Oriented Development
Page 64: Object Oriented Development
Page 65: Object Oriented Development

Format of a classFormat of a class

[visibility] class ClassName{[properties] the order[constructor methods] does not[methods] matter

}

Page 66: Object Oriented Development

Introduction to two classesIntroduction to two classes

StringHolds fixed length, non-changeable strings.

StringBufferHolds variable, changeable length strings.

Page 67: Object Oriented Development

StringStringInstantiation (Creating one for use)

– String blah1 = new String(“Hello”);

Fixed length, cannot change.– blah1=new String( new String(“Hello”) + new

String(“Goodbye”));

Page 68: Object Oriented Development

StringStringInstantiation

String blah1 = new String(“Hello”);

String blah2 = “Hello”;

Fixed length, cannot change.blah1 = “Hello” + “Goodbye”;

Same as blah1=new String( new String(“Hello”) +

new String(“Goodbye”));

Page 69: Object Oriented Development

StringBufferStringBuffer

A string buffer is a variable length String whose contents can be modified.

Provides methods to manipulate its contents.

Use sparingly because of performance issues, but better memory-wise.

StringBuffer y = new StringBuffer(“Hello”);

Page 70: Object Oriented Development

Calling an Object’s MethodsCalling an Object’s Methods

object.method()

Pawn p = new Pawn();p.move();int x = p.getXposition();myOven.beginBake(30,450);

Page 71: Object Oriented Development

Calling an Object’s MethodsCalling an Object’s Methods

object.method()

String cow;cow = new String(“ Hello Mr. Smith. ”);String x = cow.toLowerCase().trim();System.out.println (“[” +x + “]”);

[hello mr. smith]

Page 72: Object Oriented Development

System.out.println(String str)System.out.println(String str)

Here’s a method you’ve already used:the .println() method of the System.out object.

System.out.println (“Hello World”);System.out.println (“He is ”+ x +“ years old”);

Page 73: Object Oriented Development

Method OverloadingMethod Overloading

Creating a method with the same name, but with a different set of parameters, so either version can be called.

Using an existing method name with a different set of parameters.

A signature is the combination of a method name and its parameter types.

Creating two methods with the same signature, but with a different return type is erroneous.

Page 74: Object Oriented Development

Method OverloadingMethod Overloading

“It’s like, two, two, two mints in one…”

public void setDuration(int mins) {duration = mins;

}

public void setDuration(int hours, int mins) {duration = (hours*60) + mins;

}

Calling code:myClass.setDuration(5);myClass.setDuration(4,20);

Page 75: Object Oriented Development

DocumentationDocumentation

In Jbuilder, press [F1] http://java.sun.com/j2se/1.3/docs/api/index.html Sun Microsystems provides all of their

documentation in the JavaDoc template so that information is easy to find

Page 76: Object Oriented Development

JavaDocJavaDoc

Left-hand side lists all classes. Right-hand side lists information about a

specific class.1. An overview2. Field Summary 3. Constructor Summary4. Method Summary5. Field Detail6. Constructor Detail7. Method Detail

Page 77: Object Oriented Development

Review QuestionsReview Questions

1. What does new do?2. What is the primary difference between the

String and StringBuffer classes?3. How can you tell if a method is a constructor?4. Assuming you have a class Pie which has a

bake method. How would you write the method call on an object of class Pie referenced by the variable blueberryPie as coded below?

Pie blueberryPie = new Pie();

Page 78: Object Oriented Development

Lab 3Lab 3

Mary Had A Little Lamb

Topics:String ManipulationUsing the Doc set

Page 79: Object Oriented Development

VisibilityVisibility

Visibility is useful in hiding properties or methods that could be potentially harmful to other classes.

Types of Visibility– public - accessible to all

– private - accessible to none

– package – accessible to all classes in the package

– protected - only specific classes gain access

Page 80: Object Oriented Development

OperatorsOperators Type of operators

– Arithmetic– Assignment– Equality and Relational– Memory Allocation– Conditional– Incremental/Decremental

Unlike C and C++, you can not overload operators

Page 81: Object Oriented Development

Arithmetic OperatorsArithmetic Operators

Binary operators for algebraic computation, logical expressions and bit shifting

List of Arithmetic Operators+ - * /

% &^ |>> >>>>> ~

Page 82: Object Oriented Development

Assignment Operator (=)Assignment Operator (=)

Binary operator that assigns the variable or reference on the left to the expression on the right.

Page 83: Object Oriented Development

Special Assignment Operators Special Assignment Operators

Operators that combine arithmetic operations with the assignment operator

Increases readability and performance List of Special Assignment Operators

+= ~= -= *= /= %= &= ^= |= <<= >>= >>>=

Page 84: Object Oriented Development

Equality & Relational OperatorsEquality & Relational Operators

Used primarily in conditional statementsEquality operators used with reference

variables determine only if an object is the same, not if its properties all match

Equality Operators == !=

Relational Operators > < >= <=

Page 85: Object Oriented Development

NotNot

! NOT

boolean done = true;if (!done) { System.out.println(“keep going”);}

Page 86: Object Oriented Development

And and OrAnd and Or

&& AND

if ((a==1)&&(b==2)) {do something;

|| OR

if ((a==1)||(b==2)) {do something;

Page 87: Object Oriented Development
Page 88: Object Oriented Development

Incremental / Decremental Incremental / Decremental OperatorsOperators ++ or -- before a variable means that the value

should be appropriately incremented or decremented, then evaluated

Incremental or decremental operators may only be used on variables or expression that can be on the left side of an assignment operator.

a++; a--;quantity++; quantity--;++remaining; --remaining;

Page 89: Object Oriented Development

Incremental / Decremental Incremental / Decremental OperatorsOperators ++ or -- after a variable means that the value

should be evaluated, then appropriately incremented or decremented.

int a = 1; if (a++ == 2) {

System.out.println (“Hello”); }

int a = 1; if (++a == 2) {

System.out.println (“Hello”); }

Page 90: Object Oriented Development

Control FlowControl Flow

Sequence structureSelection structures

if if/elseswitch

Repetition structures forwhiledo/while

Page 91: Object Oriented Development

Sequence StructureSequence Structure

General structure of Java programs. Unless told otherwise, continue on to the

next line of code.

Page 92: Object Oriented Development

Try / Catch / FinallyTry / Catch / Finally

These control structures handle errors. try

– A block of code to be processedcatch

– A block of code that is called if the try failsfinally

– A block of code that is processed regardless of the success of the try

Page 93: Object Oriented Development
Page 94: Object Oriented Development

Selection Structure - Part ISelection Structure - Part I

Using if– Process if block when the condition is

successfully met; otherwise, ignore it.Using if/else

– Process if block when condition is successfully met; otherwise, process else block

Page 95: Object Oriented Development

Selection Structure – Part IISelection Structure – Part II

Using switch– Allows for multiple selections– Process each case block when the condition is

successfully met. If no case is met, process default block if it exists.

Page 96: Object Oriented Development
Page 97: Object Oriented Development

Repetition Structures – Part IRepetition Structures – Part I

Using for– Keeps processing for block if the loop condition is

met.

for (initial; termination; increment) {block;

}

for (i=1; i<10; i++)

for (int i=1; i<10; i++)

for (int i=1; (i<10)&&(!done)); i++)

Page 98: Object Oriented Development
Page 99: Object Oriented Development

Repetition Structures – Part IIRepetition Structures – Part II

Using while

– Keeps processing while block if the loop condition is met

while(condition){

block;

}

You must make sure the condition eventually becomes false!

Page 100: Object Oriented Development
Page 101: Object Oriented Development

Repetition Structures – Part IIIRepetition Structures – Part III

Using do/while– Processes do block at least once before testing

the loop condition to continue with processing

do{block;

} while(condition)

You must make sure the condition eventually becomes false!

Page 102: Object Oriented Development
Page 103: Object Oriented Development

StringTokenizerStringTokenizer

The StringTokenizer class allows an application to break a string into tokens.

Tokens are determined by delimiters. Example: Spaces act as delimiters in sentences.

We recognize words in a sentence as tokens.

StringTokenizer st; st = new StringTokenizer("this is a test");

while (st.hasMoreTokens()) { System.out.println(st.nextToken());

}

Page 104: Object Oriented Development

Review QuestionsReview Questions

1. What does count++ mean?2. What does x += 3 mean?3. What is the difference between

== and = ?4. What keywords in Java are used for

exception handling?5. In the for loop, what are the three parts

(names not important, just purpose)? for (a; b; c)

Page 105: Object Oriented Development

LabLab

StringTokenizer

Topics:StringTokenizerLoopsUsing the Doc set

Page 106: Object Oriented Development

InheritanceInheritance

A subclass is a class that inherits from another class

Page 107: Object Oriented Development

Using Using extendsextends

The extends keyword follows the class name

Example: class Employee extends Person

This example allows Employee to use all of the properties and methods of Person

Page 108: Object Oriented Development

InheritanceInheritance

All public methods of inherited class can be called by the subclass (the inheritor)

All public properties of the inherited class can be referred to by the subclass (the inheritor)

public class Pawn extends ChessPiecepublic class BigFinnedRocket extends Rocket

Page 109: Object Oriented Development

Method OverridingMethod Overriding

Like blotting-out the parent’s method with a new method.

Replacing an inherited method.New method must have the same

argumentsNew method must have the same return

data type.

Page 110: Object Oriented Development

Review QuestionsReview Questions

1. What does extends mean?2. What is the difference between

overloading and overriding?3. Why does the main method of a class

that you want to run from the command line (when loading the JVM) need to be static?

Page 111: Object Oriented Development

LabLab

Vegetables

Topics:InstantiationInheritanceOverriding

Page 112: Object Oriented Development

staticstatic

Static is a modifier of both methods and properites

It means:– “There is only one of these.”– “This exists always.”

Page 113: Object Oriented Development

staticstatic Our main methods so far:

public class Vegetable {

static void main (String[] args) {do stuff

}}

The line we’ve had you erase:

public class Vegetable {

static void main (String[] args) {Vegetable vegetable1 = new Vegetable();

do stuff

}}

Page 114: Object Oriented Development

Databases and JDBCDatabases and JDBC

Java Database ConnectivityJDBC is a database neutral library for

accessing information from SQL-92 compliant databases that have JDBC package.

To use JDBC you need to import java.sql.*Need to handle SQLException in most

cases.

Page 115: Object Oriented Development

JDBC classesJDBC classes

Connection– Link to a database

Statement– sql statements (select, update, delete)

ResultSet– holder for returned data

Page 116: Object Oriented Development

ConnectionConnection

A class that maintains a session with a specified database.

First, load the appropriate JDBC driverSecond, create a new Connection object

with the DriverManager:

Class.forName(jdbcDriver); //load the driver

Connection conn = DriverManager.getConnection(url, “user”, “pw”);

Page 117: Object Oriented Development

StatementStatement

Statement – SQL commands that are sent to the database

PreparedStatement – Same – but better!SQL commands that are precompiled and therefore more efficient than Statement

CallableStatement - used to execute SQL stored procedures.

PreparedStatement stmt;stmt = conn.prepareStatement(“select…..”);

Page 118: Object Oriented Development

ResultSetResultSet

Structure that maintains the rows of data returned from a SQL command.

Product of a Statement executionAllows simple navigation of the rows.

Page 119: Object Oriented Development

StatementStatement.executeQuery().executeQuery()

A method of Statement that executes a an SQL command and returns a ResultSet

Used mostly with SQL statements that use the SELECT command

Returns a ResultSet

ResultSet rs;rs = stmt.executeQuery();

Page 120: Object Oriented Development

StatementStatement.executeUpdate().executeUpdate()

A method of Statement that is used to execute SQL statements that utilize UPDATE, INSERT, and DELETE.

Page 121: Object Oriented Development

Review QuestionsReview Questions

1. What is the jdbc Connection used for?2. What is the difference between the

Statement’s executeQuery() and executeUpdate() methods?

3. What is the difference between Statement and PreparedStatement?

Page 122: Object Oriented Development

Setup ODBC link now.Setup ODBC link now.

Control PanelData Sources odcbNew System datasourceAdd new reference to JavaLesson on

seg01Username: StudentPassword: learning

Page 123: Object Oriented Development
Page 124: Object Oriented Development
Page 125: Object Oriented Development
Page 126: Object Oriented Development
Page 127: Object Oriented Development

Windows ODBC driverWindows ODBC driver

You have now created a windows ODBC link to the JavaLesson database.

You can now refer to this database from:– Excel, Word, Visual Basic, Java, etc…

Java has a JDBC / ODBC driver.This is the driver we’re going to use.

Page 128: Object Oriented Development
Page 129: Object Oriented Development

Lab 8Lab 8

Who Stole My Cookie – jdbc VersionPurpose:JdbcConnectionPreparedStatementResultSet

Page 130: Object Oriented Development

Object Oriented DevelopmentObject Oriented DevelopmentJava

Part II

Page 131: Object Oriented Development

Web ServersWeb Servers

Fancy File Servers

Page 132: Object Oriented Development

BrowserBrowser

An application which allows you to view html files.

http://bgcc.globe.com/hello.html

Means: Display the file hello.html which is available from the web server bgcc.globe.com

Page 133: Object Oriented Development

Hypertext Markup LanguageHypertext Markup Language(HTML)(HTML)Widely used to generate web pagesAllows for simple formattingSmall vocabulary of tags

Page 134: Object Oriented Development

HTMLHTML

Begin Tags and End TagsFormat: <tag> stuff </tag>Every html document begins with

<html>

Every html document ends with

</html>

Page 135: Object Oriented Development

<body><body>

Separates the <head> from the <body>

<html>special header stuff

<body>viewable content

</body></html>

Page 136: Object Oriented Development

TagsTags

Things tags are used for:– Format text– Insert Graphics– Colors– Display data in table format– Link to other pages– Insert sounds

Page 137: Object Oriented Development

CommentsComments

Format:

<!-- comments -->

Page 138: Object Oriented Development

<h1> <h2> <h3><h1> <h2> <h3>

Header lines. Like Headers in Microsoft Word.

<h1>Information Technology</h1><h2>Employee List</h2><h3>Lower Level</h3>

Information TechnologyEmployee ListLower Level

Page 139: Object Oriented Development

<p><p>

Paragraph. Used because carriage returns and line-feeds in

source document are ignored.

<p>The cow went to the stream. The water was cold.</p><p>Hello</p>

The cow went to the stream. The water was cold.

Hello

Page 140: Object Oriented Development

<br/><br/>

Break line. Used because carriage returns and line-feeds in

source document are ignored.

<p>The cow went to the<br/> stream. The water was cold.</p><p>Hello</p>

The cow went to the stream. The water was cold.

Hello

Page 141: Object Oriented Development

<b> <i><b> <i>

<b> is bold<i> is italics.

<b>Notice:</b> Don’t <i>drink</i> the water.

Notice: Don’t drink the water.

Page 142: Object Oriented Development

TableTableUsed whenever you need to line up

columns<table> <tr> <th><td>

<table> <tr> <th>First Name</th> <th>Last Name </th></tr> <tr> <td>John</td> <td>Adams</td> </tr> <tr> <td>Abraham</td> <td>Lincoln</td> </tr> <tr> <td>George</td> <td>Bush</td> </tr></table>

Page 143: Object Oriented Development

ListListUnordered List <ul> <li>

<html><body>

Before you go, pick up:<ul><li>Food packs</li><li>Compass</li><li>Map</li></ul>

</body></html>

Page 144: Object Oriented Development

ListsListsOrdered List <ol> <li>

<html><body>

Follow these steps:<ol><li>Check your parachute</li><li>Move to the door</li><li>Jump</li></ol>

</body></html>

Page 145: Object Oriented Development

AttributesAttributes

Many tags have attributes.

Format:<tag attribute1=setting attribute2=setting> stuff </tag>

Page 146: Object Oriented Development

<table<table border border=#>=#>

<table border=1> <tr> <th>First Name</th> <th>Last Name </th></tr> <tr> <td>John</td> <td>Adams</td> </tr> <tr> <td>Abraham</td> <td>Lincoln</td> </tr> <tr> <td>George</td> <td>Bush</td> </tr></table>

Page 147: Object Oriented Development

bgcolorbgcolorSet the background color.

<html>

<body bgcolor="green"><b>The grass is always greener on the other side

of the fence.</b>

</body></html>

Page 148: Object Oriented Development

bgcolor in Tablesbgcolor in Tables <table border=1> <tr bgcolor="yellow">

<th>First Name</th> <th>Last Name </th> </tr>

<tr> <td>John</td> <td>Adams</td> </tr> <tr> <td>Abraham</td> <td bgcolor="lightblue">Lincoln</td> </tr> <tr> <td>George</td> <td>Bush</td> </tr> </table>

Page 149: Object Oriented Development

Color Codes in Hex FormatColor Codes in Hex Format

Page 150: Object Oriented Development

Anchor / HyperLinkAnchor / HyperLink

A link to another location.<a href=“location”> stuff </a>

<html> <body> <h1>Hello world</h1> <p>Welcome to my town.</p> <p>Now please<a

href=“http://bgcc.globe.com”>go home</a>! </body> </html>

Page 151: Object Oriented Development

<font><font><html>

<body>The grass is <font size=+2>always</font><font color="green" face="script"

size=+5>greener</font> on the <font face="junius">other side</font> of the

fence.</b>

</body></html>

Page 152: Object Oriented Development

<img><img>

<img src=“filename”/>

<html><body bgcolor="000000" text="FFFFFF"><h1>Hello world</h1><img src="c:\pics\60gunner.gif"></body></html>

Page 153: Object Oriented Development

Lab 12Lab 12

Hello World Web Page

Page 154: Object Oriented Development

Lab tagsLab tags

<h1>…</h1> <p>…</p> <font color=“xxxxxx”>…</font> <img src=“…”/> <table> <tr> <th> <td> Bgcolor border <a href=“…”>….</a> <center>…</center> <hr/> <i>…</i> <b>….</b>

Page 155: Object Oriented Development

HTML FormsHTML Forms

<form><input><select>

– <option>

Page 156: Object Oriented Development

<form><form>

<form name=name action=action method=method>

Page 157: Object Oriented Development

<input><input>

<input type=type name=name value=value>

<input type=“text” name=name value=value><input type=“radio” name=name value=value> <input type=“hidden” name=name value=value><input type=“checkbox” name=name value=value><input type=“submit” name=name value=value>

Page 158: Object Oriented Development

<select><select>

<select name=name><option selected value=value1>Stuff1<option value=value2>More Stuff<option value=value3>Yet More Stuff<option value=value4>Yet Still More

Stuff</select>

Page 159: Object Oriented Development

Get and PostGet and Post

Both send the variable names and their values back to the web server.

Get– Shows them in the URL line.– Whenever the URL is typed in, it is a “get”.

Post does it behind the scenes.– Can only be done from submits of forms.– Better when sending a lot of data because it

looks cleaner – no other reason.

Page 160: Object Oriented Development

GetGet

Page 161: Object Oriented Development

Web ServersWeb Servers User web browser requests a file from web server. Server loads the file and sends it back to the

browser. With a plug-in, the web server is able to send back

files that are created on demand. Sort of like going the drive-up window of a burger

joint. When you order (you are the browser, clerk is the server), you don’t know, whether your burger is created “on the spot” or was “prepared in advance.” If it is prepared on the spot for you, you’ll be able to add qualifications and change the burger to fit your specific needs.

Page 162: Object Oriented Development

ServletsServlets

Servlets allow web surfers to see “live” data instead of a previously prepared page.

Often, previously prepared pages are referred to as “static” pages.

Servlets allow you to produce “dynamic” pages. User’s web browser does know that the returned

page was created on the spot. To the browser, it looks no different than a regular page.

Page 163: Object Oriented Development

ServletsServlets

Web server plug-ins allow the web server to call a “servlet” which will create a page “on-the-fly” and pass this page back to the browser.

You can write java classes which write their output to a web server.(instead of the console: System.out.println).

Page 164: Object Oriented Development

ServletsServlets

If you were to write a servlet from scratch, it would be painful.

With Object Oriented Technology and inheritance,you can inherit all the necessary properties and methods and merely extend them to meet your specific needs.

Page 165: Object Oriented Development

ServletsServlets

You will need to import the following:– import javax.servlet.*;– import javax.servlet.http.*;

If you plan to access a database,don’t forget to import:– import java.sql.*;

Page 166: Object Oriented Development

Extending HttpServletExtending HttpServlet

You class needs to extend HttpServlet

public class WebReport extends HttpServlet {

}

Page 167: Object Oriented Development

Requests and ReponsesRequests and Reponses

An object of the Request class will hold information regarding what data the user browser is requesting from your servlet.

An object of the Response class will enable your servlet to send a response to the user browser.

Page 168: Object Oriented Development

doGet() doGet() The web server that will call your servlet will specifically call

your doGet() method so you better have one… and it better look like this…

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

your stuff here…

}

because that’s the signature of the doGet() method that the web server is going to call…

because that’s how programmers who created the web server wrote it!

Page 169: Object Oriented Development

HttpServletRequestHttpServletRequest

getParameter() method of HttpServletRequest

String eDate = req.getParameter("eDate");String runCode = req.getParameter("runCode");String pCode = req.getParameter("productCode");

Page 170: Object Oriented Development

HttpServletResponseHttpServletResponse

PrintWriter out;out = res.getWriter();res.setContentType("text/html");out.println("<html>”);out.println(“<head>”);out.println(“<body>”);out.println(“<h1>Hello World</h1>”);out.println("</body>");out.println("</html>");

Page 171: Object Oriented Development

Reading from the Web ServerReading from the Web Server

Page 172: Object Oriented Development

Printing to the Web ServerPrinting to the Web Server

Page 173: Object Oriented Development
Page 174: Object Oriented Development
Page 175: Object Oriented Development
Page 176: Object Oriented Development
Page 177: Object Oriented Development
Page 178: Object Oriented Development
Page 179: Object Oriented Development
Page 180: Object Oriented Development
Page 181: Object Oriented Development

Lab 13Lab 13

Hello World Servlet

Page 182: Object Oriented Development

Lab 14Lab 14

Database Servlet

Page 183: Object Oriented Development

Arrays and VectorsArrays and Vectors

Page 184: Object Oriented Development

ArraysArrays

An array is a fixed-length structure that stores multiple values of the same type.

Car c = new Car[10];Car[] c = null;

Page 185: Object Oriented Development

VectorsVectors

A vector is a variable-length structure that can store values of many data types.

Vector vCar = new Vector(10);

Page 186: Object Oriented Development

Using the Using the instanceofinstanceof operator operator

Binary operator that determines whether the object on the left is a member of the class on the right.

if (c instanceof Car)

Page 187: Object Oriented Development

Review QuestionsReview Questions

1. What is one restriction that an array has the a Vector does not?

Page 188: Object Oriented Development

LabLab

Missile Arrays and Family FunArraysVectors

Page 189: Object Oriented Development

Using Using implementsimplements

The implements keyword follows the class name

Example:class Employee implements Comparable

This means that Employee must contain the methods defined in the Comparable interface.

Page 190: Object Oriented Development

Review QuestionsReview Questions

1. What does extend mean?2. What is the difference between

overloading and overriding?3. What is the difference between extends

and implements?

Page 191: Object Oriented Development

File I/OFile I/O

Every file is seen by Java as a byte stream.To use file, one must use the java.io.*

packageNeed to handle IOException in most cases

Page 192: Object Oriented Development

FileInputStream & FileInputStream & FileOutputStreamFileOutputStreamClasses used to access the contents of a

fileSends and receive the data as byte streams

Page 193: Object Oriented Development

InputStreamReaderInputStreamReader

Readers view the data as character streams.

Page 194: Object Oriented Development

BufferedReaderBufferedReader

Buffers allow for data to be collected before an action takes place

BufferedReaders use buffers to read character based streams.

Page 195: Object Oriented Development

Review QuestionsReview Questions

1. How do you know when to use BufferedReader versus other readers?

Page 196: Object Oriented Development

LabLab

Who Stole My Cookie – File Version

Topics:File I/O

Page 197: Object Oriented Development

NetworksNetworks

A collection of computers that have some medium of communication

Networks are passive entities that can’t interpret any of the data being transmitted.

One of Java’s strengths is its robust handling of network programming

Page 198: Object Oriented Development

TCP/IPTCP/IP

A protocol that maintains the order of data transmitted over a network.

TCP/IP is reliable because it reports an error if any of the data is not transmitted properly.

IP addresses are unique identifiers of computers in a network.

Page 199: Object Oriented Development

PortsPorts

A 16 bit number that is used by TCP/IP to deliver data to an application on a server

An analogy:– A telephone number is to an IP address as an

extension number is to a port.

Page 200: Object Oriented Development

ProtocolsProtocols

Rules that determine how the server and client applications communicate with each other.

Examples:HTTPFTPTELNETTIME

Page 201: Object Oriented Development

SocketsSockets

A Java Class that provides an input and output stream to a named port.

Similar to File I/OTo use the Socket class: import java.net.*;

Page 202: Object Oriented Development

Review QuestionsReview Questions

1. What is a port?2. What is a socket?

Page 203: Object Oriented Development

Lab 9Lab 9

Echo & Pig Latin ServerSockets

Page 204: Object Oriented Development

ThreadsThreads

Threads allow for multi-tasking. Threads eliminate unnecessary idle time.To use threads, you may make a subclass

of Thread.

Page 205: Object Oriented Development

SleepSleep

Threads can be placed in a state of sleep. They will remain dormant for a pre-determined time.

Threads will only leave the sleep state when an interrupt is called or the predetermined time expires.

When a process halts, all its child threads stop functioning.

Page 206: Object Oriented Development

Using synchronizedUsing synchronized

The synchronized keyword is used to lock methods or code blocks.

Locking a method or code block queues other threads attempting to access the method or code block.

Page 207: Object Oriented Development

wait / notify / notifyAllwait / notify / notifyAll

The wait method places the thread in a dormant state for either a specified time or until the notify method is called.

notifyAll sends a message to all threads to attempt to run

Page 208: Object Oriented Development

Review QuestionsReview Questions

1. What are two ways to make a thread hibernate?

Page 209: Object Oriented Development

Lab 10Lab 10

Pig Latin Server Goes Berserk

Topics:Threads

Page 210: Object Oriented Development

ServersServers

An application that waits for other applications or instances to connect to it.

Page 211: Object Oriented Development

ServerSocketServerSocket

Need to import java.net.* and java.io.*Primary function is to wait and accept

socket connections.Example:

Socket clientSocket = null;ServerSocket serverSocket = null;serverSocket = new ServerSocket(4004); // 4004 is the porttry{

clientSocket = serverSocket.accept();}catch(IOException){

//handle the socket error}

Page 212: Object Oriented Development

Review QuestionsReview Questions

1. What is the difference between Socket and a ServerSocket?

Page 213: Object Oriented Development

Lab 11Lab 11

Instant Messenger

Topics:ServerSocket

Page 214: Object Oriented Development

ReferencesReferences

The Java Programming Language, by Ken Arnold and James Gosling, Addison-Wesley, 1999, ISBN 0-201-31006-6

Java: An Introduction to Computer Science Programming, Walter Savitch, Prentice-Hall, 2001, ISBN 0-13-031697-0

Java: How to Program, H.M Deitel and P.J. Deitel, Prentice-Hall, 2002, ISBN 0-13-034151-7