1 Introduction to Object-Oriented Programming and Java.

Post on 18-Dec-2015

223 views 3 download

Tags:

Transcript of 1 Introduction to Object-Oriented Programming and Java.

1

Introduction to Object-Oriented Programming and Java

2

Java Historical Aspects Software engineers tried to write

portable software April 1991, “Green” conducted by Sun

to develop a system for developing consumer electronics’ logic– realized the needs of a platform

independent environment.

3

Historical Aspects, cont.. May 23, 1995 the Java Environment

was announced by Sun Microsystems. Popular browsers, such as Netscape

Navigator and Internet Explorer, incorporate Java-based technology.

Stand alone environments developed.

4

Versions of JavaThree major versions released by Sun: Java 1.0.2 - still most widely supported by

browsers Java 1.1.5 Spring 1997, improvements to user

interface, event handling. Java 2 - released in December 1998.

Check:

http://java.sun.com

for JDK

5

Java 2 Swing - new features for creating a

graphical user interface Improvements to audio features Drag and drop

6

Introduction to Java Java Overview

– Java is a (relatively) New Object-Oriented Programming Language.

– Designed for the network.– Java syntax is simple.– Java is platform neutral.

7

Introduction to Java Java Overview

– Secure, High performance.– Multi-Threaded.– Java is defined with a very comprehensive

class and object libraries (packages).

8

Introduction to Java New Object-Oriented Language

– All data structures, and programs that operate on it are encapsulated in the context of objectsobjects.

– Code reuse is supported by Java's inheritanceinheritance properties.

9

Introduction to Java Designed to run on the net.

– Net could be the Internet or an Intranet.– Built-in networking capability in a language

package Java.net– Support client/server computing between

different computers.

10

Introduction to Java Java is relatively simple yet powerful

– Java’s syntax is based on C & C++ syntax that makes it easy to learn.

– Java forbids the use of pointers. Java automatically handles the referencing and de-referencing of objects. Eliminates memory leaks.

– Rich pre-defined classes for I/O, net, & graphics.

11

Introduction to Java Java can be “platform neutral”.

– Java can be an interpreted language. Programs are interpreted to an intermediate optimized form called “byte-byte-codecode”

– The run-time interpreter reads the byte-byte-codecode and executes using a model of an abstract machine (JVM).

12

Introduction to Java Java can be “platform neutral”.

– Java virtual machine converts byte-code to the specific machine code.

– JVM & interpreter perform a very strong type checking.

– Built-in Java memory model that performs “garbage collection” to prevent memory leaks.

13

Introduction to Java Java Applet Security.

– No Pointers.– Memory allocations and de-allocations are

handled by JVM.– Byte-code verification every time an applet

is loaded.

14

Introduction to Java High Performance

– Compared to other interpreted languages such as Basic, Visual Basic, etc. Java is much faster.

– Although 20 times slower then C/C++, with JIT-compilers Java’s speed is somewhat comparable.

– Compiled Java is as fast as other compiled languages

15

Introduction to Java Java is Multi-Threaded

– Native support for multi-tasking in the form of multi-threading.

Multi-Threading = Several lines of execution run independently and simultaneously.

16

Introduction to Java

ClassClass is the basic building blockis the basic building block– The reserved word class class indicates the

beginning of a new class

Syntax: (constructs in [ ] are optional)

[<qualifier>] classclass classname [extendsextends classname1] [implementsimplements interfacename]

{

….. Class body;

}

17

Introduction to Java <class_qualifier> is one of the following

reserved keywords– publicpublic– privateprivate– abstractabstract– finalfinal

18

Introduction to Java What’s in the class body?

– Data members– Methods/messages that operate on the

data.

19

Introduction to Java

Data Members Syntax:[<access_qualifier>] <Member type> MemberName;

– Access qualifier can be one of the following• public finalpublic final• private protectedprivate protected• staticstatic

– Member Type• int, long, short, float, double, byteint, long, short, float, double, byte or a class

name

20

Introduction to Java Methods/Messages Syntax:

<access_qualifier> <return_type> methodName (arg1, arg2, …, argN)

{

method_body

}

21

Java Methods <access_qualifier>

– public privatepublic private– protected abstractprotected abstract– finalfinal

<return_type>– void, int, long, floatvoid, int, long, float, … or class name

22

Introduction to Java Application are either:

– Stand-alone.– Browser-Based.– Or both.

23

Introduction to Java

Stand-alone application– In a stand-alone application, JAVA’s run-

time transfers execution to a specific method named mainmain

– The main method must be defined as publicpublic and static static and should return no value voidvoid.

– And one parameter as an array of Strings

24

Introduction to Java

Example:classclass HelloWorld {

… methods and members

public static void mainpublic static void main(String Args[]) {

// method body

}

… more methods

}

25

Introduction to Java Simple Stand-alone application

class HelloWorld {

public static void mainmain(String Args[]) {

system.out.println(“Hello World\n”);

}

}

26

Introduction to Java

Browser-Based Application (Applet)– Must derive from java.applet.Applet– Must define the following methods

• public voidpublic void init()• public voidpublic void start()• public voidpublic void stop()• public voidpublic void destroy()• public voidpublic void paint(Graphics g)

27

Introduction to Java

Let’s put it together - structure of Java programOptional Package Statement

Optional import Statements

Class Definition(s)

A Class Definition

main() and/or init(),start(),stop(), destroy() are defined

28

Introduction to Java

Language Constructs and Semantics– Data types & Variables – Operators– Statements

• Expression• Block• Assignment• Flow Control

– Classes

29

Introduction to Java

Built-in data types - integer numbersinteger numbers– byte = 8-bit signed integer -128 to +127– short = 16-bit or 2-byte signed integer– int = 32-bit or 4-byte– long = 64-bit or 8-byte.

30

Introduction to Java

Built-in data types - Real NumbersReal Numbers– float = 32-bits– double = 64-bits

Both float and double are defined according to IEEE 754-1975.

31

Introduction to Java Built-in data types - characters & stringscharacters & strings

– Sequence of characters enclosed in double quotes are string literals - string literals - string is not a string is not a type. type. String is class

Ex:

“blue” ‘A’

“black dog” ‘c’

“1st line\n2nd line”

32

Introduction to Java Built-in data type - Boolean

– Boolean = can hold two values (true,falsetrue,false)– Boolean variables can only be involved in

logical operation or expressions that evaluate to (true or false)

33

Introduction to Java Variables must start with a letter

followed by any number of lettersletters, digitsdigits, underscoreunderscore ( _ )or the dollar signdollar sign ($).

Ex: MyHouse valid

Her_Car_$ valid

My_2nd_Car valid

12_ab_$ Invalid

34

Introduction to Java Arithmetic Operators:

– Binary operators• *, / multiplication and division• +, - addition and subtraction• % remainder• <<, >> shift left and shift right.• >>> shift-right fill zero extension.

35

Introduction to Java Arithmetic Operators

– Unary Operators• ++, -- increment and decrement they can

appear before the variable and is called pre-incrementing or pre-decrement

ex: ++a , --b and are equivalent to a=a+1, b=b+1.

• - unary negative sign.

36

Introduction to Java

Assignmenta = b

for basic types, old value of a disappears to be replaced by the value of b.

for objects a and b are pointing to the same object that is the object b is pointing to.

a += b, is the same as a = a + b

a -= b is the same as a = a - b

a *= b is the same as a = a * b

37

Introduction to Java Expressions

– Operators are evaluated left-to-right.– Operators are grouped into16 precedence

level.

38

Introduction to Java Java evaluates expressions with mixed

data types.– Implicit conversion occurs among basic

data type byte, int, short, long, float, double– Implicit conversion promote types in an

attempt to preserve precession.

39

Introduction to Java Block statement

– any number of statements enclosed within a pair of curl-brackets { }

– Examples• body of main()• body of class• for any reason

40

Introduction to Java

Flow control statements (conditional)– ifif (BooleanExpression)

statements-block-1

[ elseelse

statements-block-2 ]

when BooleanExpression evaluates to true block-1 is executed, otherwise block-2 if it exists.

41

Introduction to Java

True FalseBoolean Expression

JavaStatements

JavaStatements

If-then-else

42

Introduction to Java

True

False

Boolean Expression

JavaStatements

If-then

43

Introduction to Java

Flow Control statements (branching)– switchswitch (expression)

casecase const_1: statement-block-1

casecase const_2: statement-block-2

casecase ….

[defaultdefault: statement-block-n ]

value evaluated for expression should match one of the const_n otherwise the default-block is executed.

44

Introduction to Java

Eval. switch

C1?

C2?

C3?

True

Fal

se

45

Introduction to Java

Flow Control (branching)– Break Break [label]– continuecontinue [label]– returnreturn [ expression]

All three statement cause execution to branch to the Label or return to the calling program.

46

Introduction to Java Control Flow (repetition)

– whilewhile (BooleanExpression)statement-block

– dodo statement-block whilewhile (booleanExpression)

– forfor (exp1; BooleanExpression; exp2)statement-block

47

Introduction to Java

Ex?

Fal

seT

rue

While-stmt

48

Introduction to Java

Ex?False

Tru

e

49

Introduction to Java

Eval I

Is I?

Inc.

50

Introduction to Java Classes - definition

[<modifiers>] classclass <classname> {

class_methods and Data …

} <Modifiers>

– publicpublic - protectedprotected -abstractabstract– privateprivate - finalfinal

51

Introduction to Java

Method signature = method name & parameters type & order of parameters

method return value is not part of the signature.

Same name Methods in the same class or derived classes are called overloaded.overloaded.

52

Introduction to Java

Arrays– Basic types

• int a[] = new int[10] array of 10 integers.

• Int[] a = new int[10]

– Objects• fish[] f = new fish[9]; creates place holders for 9 fish. the class

name is used as a type

• to create the 9 instances of fish try the following code: (notice the use of constructor to create instances)

for (int I=0; I<10; I++)

f[I] = new fish(2*I, 1, 2*I);

53

Introduction to Java

Multi-dimensional arrays• int mat[][] = new int[10][20]; 10x20 matrix.• Int[][] mat = new int[15][] 15 row matrix

– for (int I=0; I<15; I++)

mat[I] = new int[I+1];

This will create a lower triangular matrix

54

Introduction to Java Classes as user-defined types

– Syntaxclassname <variablename>

– ExampleMyClass C; // creates a “place holder”/reference

to an objectobject C of typetype MyClass

To assign an object to CC = newnew MyClass();

55

Introduction to Java More Examples

MyClass C1;

MyClass C2;

C1 = newnew MyClass();

C2 = C1; // C2 and C1 are two distinct objects?

NO

C1 and C2 are pointingpointing to the same object.

56

Introduction to Java

C1

C2

A C

lass

57

Introduction to Java How do we create two separate

objects?C1 = newnew MyClass();

C2 = newnew MyClass();

58

Introduction to Java Basic data types are different

int a; // a is a real object it is not a reference

int b; // b is too and it occupies a different location in memory

a = 7;

b = a; // will assign the value 7 to b.

59

Introduction to Java Type Wrapper Classes - What are

they?– Are Java classes that encapsulate the

basic data types.– Are Java classes that defines additional

methods on the basic data types

60

Introduction to Java Type Wrapper Classes - Distinguish?

– Integer // full word instead of int– Long // First letter is capital– Character– Double– Float– Boolean

61

Introduction to Java Type Wrapper Classes - Common

methods– publicpublic basictype classtypeValue()– publicpublic classtype( basictype)– publicpublic String toString()– publicpublic boolean equals( Object )– publicpublic int hashCode()

62

Introduction to Java

Example - The “Integer” wrapperclassclass Integer {

publicpublic Integer( intint a ) { … } // as constructor

publicpublic intint IntegerValue() { … }

publicpublic String toString() { … }

publicpublic booleanboolean equals( Object Obj) { … }

….

}

63

Introduction to Java How Do we use them?

a = new Integer(33);

b = new Integer(14);

if (a.equals(b)) {

system.out.println(“a is equal to b”);

}

int c = a.IntegerValue();

64

Introduction to Java Character Wrapper - Additional

– public static boolean isLowerCase(char c)– public static boolean isUpperCase(char c)– public static int digit(char c, int radix)– public static boolean is Digit(char c)– public static char forDigit(char c) …

• Note: All methods are static !!!

65

Introduction to Java More Methods for Integer, Long Float,

and Double– public final static datatype MIN_VALUE;– public final static datatype MAX_VALUE;– public static classtype valueOf(String s);– public static final datatype NaN;– public static final datatype

NEGATIVE_INFINITY ...

66

Introduction to Java Is that All? Definitely Not

– More and more methods - Where can you find them?

• On-line Documentation

67

Introduction to Java Basic Input/Output classes

– All Java I/O operations are defined in the java.io package

– Only two classes are exposed in this session

• FileOutputStream• PrintStream

68

Introduction to Java FileOutputStream

– use this class to write data to fileEx: FileOutputStream F = new

FileOutputStream(“afile.dat”);

– More Methods to write, close, flush ..• F.write(a) // a can be int, char, …• F.close() // close the file and dispose F.• F.flush() // flush the buffer

69

Introduction to Java PrintStream

– is a printing to a steam class– PrintStream requires a FileOutputStream to

be constructed a prior– to create a PrintStream instance use the

constructorFileOutputStream fos = new FileOutputStream();

PrintStream pst = new PrintStream(fos);

70

Introduction to Java Predefined PrintStream

– system.in // Keyboard input– system.out // screen output– system.error // default screen output

Methods defined for PrintStream– println, print a pair for each basic data type– println, print a pair for generic objects

71

Introduction to Java Arrays in Java

– Arrays are collection of objects, or data types that can be referenced by an index.

– Indexes identify location of object or the cells where objects are stored.

– Each object is an Element of the array.

72

Introduction to Java How do we create them?

– Syntax:type[ ] arrayname = new type[size]; // syntax #1

type arrayname[ ] = new type[size]; // syntax #2

– Examplesint a[] = new int[10];

int[ ] a = new int[100];

73

Introduction to Java

What if the size is not known until the run-time?– Syntax:

type arrayname;

– Example:int size;

int[ ] a;

size = getSizeValue(); // any method

a = new int[size];

74

Introduction to Java Can we initialize them “in-bulk” ?

– Syntax:type arrayname[ ] = { v1, v2, v3, … vn };

type[ ] arrayname = { v1, v2, v3, … vn };

– Example:• int[ ] a = { 12, 14, 16, 18, 20 }; // size is 5• char vowels[ ] = { ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ };

75

Introduction to Java Can we form collections of Objects?

Yes How do we create them?

– Create “place-holder” - step 1– Create each individual element - step 2

76

Introduction to Java

Examples:Turtles[] turtle = new Turtles[10]; // 10 cat place-

holder

for ( x=0; x<10; x++) {

turtle[x] = new Turtles(); // run the constructor

}

77

Introduction to Java Multi-dimensional arrays

– Examples:int a[ ][ ] = new int[5][10];

78

Introduction to Java More Examples:

– 3-D arraysint a[][][] = new int[10][10][5]; // 3-D array

– Variable size arraysint a[10][ ] = new int[10][ ];

for (x=0; x<10;x++) {

a[x] = new int[x+1];

} // creating a lower triangular matrix

79

Introduction to Java The String Class

– String class is an object with an array of characters with lot of methods

– Several overloaded constructors• publicpublic String(); // null string

• publicpublic String( String S); // string from a string

• publicpublic String(char[ ] s ); // string from array of char

• publicpublic String(char[ ] s, int offset, int count); ..

80

Introduction to Java String class

– Examples:String S1 = new String(“Joe Doe”);

char vowels[ ] = { ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ };

String Vowels = new String(vowels);

81

Introduction to Java

Parameter passed by value (basic types)

int aMethod( int x ) {

x++;

return x; }

a = 7;

b = aMethod(a);

system.out.println(a); // what’s the value of a

82

Introduction to Java Parameter Passing by value - (Objects)

int aMethod(Elephant E) {

E.Weight(150);

return 150; }

Elephant Mimi = new Elephant();

Mini.Weight(95);

b = aMethod(Mimi);

system.out.println(Mimi.WeightTell()); // what’s it?

83

Introduction to Java

Scope– Scope is the region in which a variable is

assumed in existence.– Regions are defined as the code inside a

block– Java compiler search for referenced

variables starting by the region in which are referenced and expand to the outer region until the variable is founf.

84

Introduction to Java

Scope

Class

{ }

Outermost Scope

{

}

{

}

{}

{}

85

Introduction to Java (2)

86

Object-Oriented Programming Is JAVA an Object-Oriented Language?

– Classes/Collections in JAVA.– Encapsulation in JAVA.– Inheritance in JAVA.– Abstraction in JAVA.– Polymorphism in JAVA.– Identity of Objects in JAVA.

87

Object-Oriented Programming Classes/Collections in JAVA.

– Everything in JAVA is defined in the context of an object.

– Objects are defined by Classes (classclass)– Example-

classclass Dogs {

….. Dogs attributes and behavior definitions

}

88

Object-Oriented Programming Encapsulation In JAVA.

– JAVA provides the implementers with four ways to classify attributes and behaviors of a class.

• Private members (privateprivate)• Public members (publicpublic)• Protected members (protectedprotected)• Friendly members (No keyword designator)

89

Object-Oriented Programming

Encapsulation in JAVA.– Example

class Dogs {publicpublic Dogs_Color;

privateprivate Dogs_Length_of_intestinal_tract

protectedprotected Dogs_genetic_material

…. Other attributes and behaviors.

}

90

Object-Oriented Programming Single-Inheritance in JAVA.

– Classes in JAVA can be defined using already defined classes and extendsextends them.

– Example

class Dolmation_dogs extendsextends Dogs {

…. Attributes and Behaviors

}

91

Object-Oriented Programming Multiple-Inheritance in JAVA.

– It is not Supported.– Indirectly JAVA provides a replacement

concept (interfaceinterface)– Several JAVA classes can provide

implementation for same interface. (implementsimplements).

92

Object-Oriented Programming Abstraction In JAVA.

– Abstract Classes (abstractabstract)• JAVA allows the implementers to define

classes with partial implementation.• Abstract classes are useful for modeling basic

behavior and leave detail implementation to subclasses

93

Object-Oriented Programming Abstraction in JAVA.

– JAVA allows classes not related by inheritance to exhibit and support same behavior/protocol through the interfaceinterface concept.

94

Object-Oriented Programming Polymorphism In JAVA.

– Three different type of polymorphism• Within the same class

– Methods same name different signature/parameters (Method overloading)

• Through inheritance (extends)– Methods same name same signature

• Through implementation of same interface.– Methods same name.

95

Object-Oriented Programming Object Instantiation In JAVA.

– New objects are instantiated in JAVA using the newnew language construct.

– Example

MyDog = newnew Dogs(Dog.Color.BLACK);

96

Introduction to Java (3)

97

Introduction to Java Structure of a JAVA Program.

– Optional PackagePackage construct.– Optional ImportImport statements.– Class implementation (classclass).– Interface implementations(interfaceinterface)

98

Introduction to Java JAVA Packages

– java.applet– java.awt, java.awt.peer & java.awt.image– java.io– java.net– java.lang– java.util

99

Introduction to Java Java.applet

– Package that enables construction of applets. It also provides information about an applet's parent document, about other applets in that document, and enables an applet to play audio.

100

Introduction to Java Java.awt

– Package that provides user interface features such as windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars and text fields. (Abstract Window Toolkit)

101

Introduction to Java Java.awt.image

– Package for managing image data, such as the setting the color model, cropping, color filtering, setting pixel values and grabbing snapshots.

102

Introduction to Java Java.awt.peer

– Package that connects AWT components to their platform-specific implementation (such as Motif widgets or Microsoft Windows controls).

103

Introduction to Java Java.io

– Package that provides a set of input and output streams to read and write data to files, strings, and other sources.

104

Introduction to Java Java.net

– Package for network support, including URLs, TCP sockets, UDP sockets, IP addresses and a binary-to-text converter.

105

Introduction to Java Java.lang

– Package that contains essential Java classes, including numerics, strings, objects, compiler, runtime, security and threads. Unlike other packages, java.lang is automatically imported into every Java program.

106

Introduction to Java Java.util

– Package containing miscellaneous utility classes, including generic data structures, settable bits class, time, date, string manipulation, random number generation, system properties, notification, and enumeration of data structures.

107

Introduction to Java JAVA application programs

– Programs without the (packagepackage) statement are application code.

– Applications are either• Stand-alone Application.• Browser-Based Application (Applet).

108

Introduction to Java Stand-alone

– In a stand-alone application, JAVA’s run-time transfers execution to a specific method named (mainmain)

– The main method must be defined as publicpublic and static static and should return no value voidvoid.

– And one parameter as an array of strings

109

Introduction to Java Browser-based Applet

– To define an application that the JAVA run-time embedded within a browser would execute one should define the following methods

• public init()public init() to initialize the application code.• public start()public start() to start/resume the application.• public stop()public stop() to stop the application• public destroy()public destroy() to unload the application.• public paint(Graphics g)public paint(Graphics g) to (re)draw the applet.

110

Introduction to Java

Object

Container

Panel

Applet

Component

111

Introduction to Java Main Features of Applets

– Code is smallsmall (few Kilobytes).– Support interactiveinteractive input from the user.– Support for multi-mediamulti-media (Audio, images).– Support Graphical User InterfaceGraphical User Interface (GUI)

elements.– Limited access to client resources

(securitysecurity).

112

Introduction to Java Creating Applets

– Derive from java.applet.Applet

Ex:

public classpublic class MyFirstApplet extendsextends java.applet.Applet {

… // Applet Code

}

113

Introduction to Java Essential methods

– One must provide implementation code for the following methods

• public voidpublic void init()• public voidpublic void start()• public voidpublic void stop()• public voidpublic void destroy()• public voidpublic void paint(Graphics g)

114

Introduction to Java public voidpublic void init()

– Called by the browser immediately after the applet is loaded.

– The method primary function is to initialize the applet

• create other objects• set & initialize parameters• load images, sound files, fonts …etc.

115

Introduction to Java public voidpublic void init() - (Cont.)

– init() is called only once by the browser during its life time, but applet code can call init() later.

116

Introduction to Java public voidpublic void start()

– after init() the browser invokes start()– unlike init(), the browser invokes start()

several times to restart a suspended applet.

– start() is generally used display images, invoke methods on other objects, create Threads for parallel processing

117

Introduction to Java public voidpublic void stop()

– stop() method is called by the browser whenever the applet is to be suspended.

– stop() method is called every time the web user leaves the page containing the applet.

– Applet is restarted by by the browser by invoking the start() method.

118

Introduction to Java public voidpublic void destroy()

– destroy() is specific designed for Java applets. Different from finalize()finalize()

– destroy() is executed once when the applet or the browser is terminated.

– destroy() is a general cleanup method - close file, stop threads, … etc.

119

Introduction to Java public voidpublic void paint(Graphics g)

– paint is called by the browser whenever the applet need to be redrawn

• resized, uncovered, moved, initialized … etc.• Graphics g, is the display device defined by the

browser (You do not have to create it)• you must override this method to create any

useful applet.

120

Introduction to Java Simple Appletpublic class HelloWorld extends Applet {

public void init() {

resize(500,500); // pixels.

}

// public void start() use default from parent

121

Introduction to Java Simple applet - (cont.)

// public void stop(), use default from parent

// public void destroy(), use default from parent.

Public void paint(Graphics g) {

g.drawString(“Hello World!”, 10, 20);

}

}

122

Introduction to Java To run a Browser-based Applet

– You must create an HTML file that contains a tag similar to:

<appletapplet codecode=“applet_name.class” [codebasecodebase=“directory”] width=w, height=h>

<paramparam param_name=value>

...

</appletapplet>

123

Introduction to Java More HTML Tags

– ALIGN= LEFT, RIGHT, TOP, TEXTOP …etc.

– HSPACE=, VSPACE= pixels– <ALT=alternate text> for not Java enabled

browser.

124

Introduction to Java The Graphics g object

– g class provides several methods• setFont()• setColor()• drawString()• standard colors (black, blue, … white, yellow).

125

Introduction to Java Simple applet II

– add the following lines• private Font StFont = new Font(“Times

Roman”, Font.ITALIC, 20);• before drawString in the paint() method add,

g.setFont(StFont);

g.setColor(Color.blue);

– And run the applet to have hello World in times roman, blue italic font.

126

Introduction to Java Passing Parameters

– Use <PARAM Param_name=Param_value><PARAM Param_name=Param_value> tag in the HTML file

– Use getParameter(Param_name)getParameter(Param_name) in the applet init(method)

– convert Param_value from String to the appropriate type using the methods defined on the type wrapper classes.

127

Introduction to Java Example - HTML Param Tags

<applet code=“Hello.class”, width=200, height=100>

<param COLOR=“red”>

<param SIZE=“36”>

</applet>

128

Introduction to Java Example - applet init() code

String color;

String size;

color = getParameter(“COLOR”);

size = getParameter(“SIZE”);

129

Introduction to Java The Graphics g Object

– it is a rectangular region– its size is specified by the resize()

invocation in init() - resize(500,500)– the unit is pixels = picture element

130

Introduction to Java

(0,0)x

y

(20)

(10)

131

Introduction to Java More Methods

– drawLinedrawLine( x_start,y_start, x_end,y_end)– drawRectdrawRect(x_top_left,y_top_left,width,height)– fillRectfillRect(x_top_left,y_top_left,width,height)– drawRoundRect(…, arc_width, arc_height)– fillRoundRect(…, arc_width, arc_height)– draw3DRect(…, true/false) raised/indented.– fill3DRect(…,true/false) .

132

Introduction to JavaH

eig

ht

Width

133

Introduction to Java More Methods

– fillOval, drawOvalfillOval, drawOval• x_top_left, y_top_left, width, height

– fillArc, drawArcfillArc, drawArc• x_top_left, y_top_left, width, height,

start_angle, sweep_angle

134

Introduction to Java

(0,0)

90

180

g.drawArc(0,0,20,20,90,180)

135

Introduction to Java Draw Polygons

– drawPolygondrawPolygon(int x[ ], int y[ ], length)– drawPolygondrawPolygon(Polygon P)– or the fillPolygonfillPolygon methods

136

Introduction to Java Draw Triangle

int x[ ] = {10, 40, 25, 10 };

int y[ ] = {60, 60, 10, 60 };

g.drawPolygon(x, y, 4); // outlined triangle

or

g.fillPolygon(x, y, 4); // filled triangle

End points

137

Introduction to Java Draw Triangle

int x[ ] = {10, 40, 25, 10 };

int y[ ] = {60, 60, 10, 60 };

Polygon triangle = new Polygon(x, y, 4);

g.drawPolygon(triangle); // outlined triangle

or

g.fillPolygon(triangle); // filled triangle

138

Introduction to Java

g.copyArea(5,5,15,10,15,10)

(5,5)

(25,15)

1510

g.clearRect(5,5,15,10)

139

Introduction to Java Applets and Fonts Information

– setFont(), getFont() are inherited from Component

– getFontMetrics(Font Fnt)– getLeading()– getAscent()– getDescent()– getHeight()– many others (straightforward).

140

Introduction to Java

Graphics

Java

Baseline

Lea

din

g

Ascent

Descent

Height = Leading+Ascent+Descent

141

Introduction to Java Java Support Multi-threading

– an application can execute multiple blocks of code (thread) in parallel.

– Issues• How do we create them• How do we manage them• How do we get rid on them

142

Introduction to Java

Th1

Th2

Tim

e

Main ThreadThread 1

Thread 2

143

Introduction to Java Threads

– Two ways to Create threads in Java• Derive & extend the “Thread” class

classclass MyClass extendsextends Thread• Implement the “Runnable” interface in you

applet.

classclass MyClass extendsextends Applet implementsimplements Runnable

144

Introduction to Java

Approach#1- extends Threadclass MyThread extends Thread {

private int a;

private int b;

String Thname;

public MyThread(String Thname,int a, int b) {

this.a = a;

this.b = b;

this.Thname = Thname

}

145

Introduction to Java

(Cont.)public void run() {for(int I=0; I<3; I++) { if (a>0) a *=a; else a = (a==0) ? 0 : a = -(a*a); if (b>0) b *=b; else b = -(a - 1); system.out.println(Thname+” a= “+a+” b=“+b); sleep(1000); // sleep 1000 milliseconds}}

146

Introduction to Java

(Cont.)public static void main(String[ ] args) {

MyThread t1 = new MyThread(“Thread#1”, 2, 0);

MyThread t2 = new MyThread(“Thread#2”, 0, 4);

t1.start();

t2.start();

} // end the main method

} // end of MyThread

147

Introduction to Java Let’s Run the Example

1. main creates th1 and th2

2. main starts th1

3. main starts th2

4. Let’s analyze the output on the next slide

148

Introduction to JavaTh1

Thread#1 a=4 b= -3

Thread#1 a=16 b= -15

Thread#1 a=256 b= -255

Th2Thread#2 a=0 b= 16

Thread#2 a=0 b= 256

Thread#2 a=0 b= 65536

149

Introduction to Java Approach #2 - Implement the

“Runnable” interface– class myClass extendsextends Aclass implementsimplements

Runnable– Ex: re-write the previous example by

extending “Object” and implement Runnable.

– Code should look the same.

150

Introduction to Java To implement a multi-threaded applet,

use the followingclass ThreadedApplet

extendsextends java.applet.Applet

implementsimplements Runnable {

… // Your Applet Code

// override the run() method

}

151

Introduction to Java

Can we manage them?– Suspend & Resume using suspend() &

resume()– stop() & start()– ask threads to yield using yield()– ask for the identity of the thread using

CurrentThread() static method.– Ask if thread isAlive()

152

Introduction to Java (4)

153

Introduction to Java Exceptions and Errors

– Error in Java is an indication of a serious problem that happened during the execution of the application.

– Error subclasses are not required to be specified in the method’s throwthrow clause.

– Errors need not be caught by the catchcatch by the application.

154

Introduction to Java Exceptions & Errors

– ExceptionsExceptions are indication of an error that the application want to catch and programmers can provide a handler for.

– Exceptions must be specified in the method’s throwsthrows clause if the method is expected to throw such an exception.

155

Introduction to Java

Object

Throwable

Error Exception

156

Introduction to Java Exceptions and Errors

– Java Language defines plenty of Error and Exception objects

157

Introduction to Java Extending The exception class

public classpublic class anException extendsextends Exception

{

publicpublic anException() { supersuper(); }

// and/or

publicpublic anException(String s) { supersuper(s); }

}

158

Introduction to Java Methods must specify the exceptions

that can be thrown any time during the method execution.<qualifier> <return_type> method(params)

throwsthrows excep1, excep2, …, excepN

{

// your code

}

159

Introduction to Java When Exceptions/Errors occur in the

method body are thrown as followspublic voidpublic void aMethod(int I) throwsthrows anException{ …. Method code if (aCondition==ExceptionCondition){ throw newthrow new anException(“a Message”); }… Method code}

160

Introduction to Java Exceptions are caught as follows

trytry block-statementcatchcatch (exception_class e) block-statement .. Handling the exceptioncatchcatch (another_exception_class e) another-block … handling this exception…finallyfinally // optional the-finally-block

161

Introduction to Java Input/Output with Java

– Java provides a framework for defining input/output classes.

– The framework defines input/output as streamsstreams

– A StreamA Stream is either output stream or input stream

– Streams are ordered sequence of of data items

162

Introduction to Java

Object

RandomAccessFileOutputStreamInputStream

163

Introduction to Java InputStreamInputStream is an abstract that class

defines the following methodspublic abstract intpublic abstract int read() throwsthrows IOException

public intpublic int read(byte b[]) throwsthrows IOException

public int readpublic int read(byte b[], int off, int len) throwsthrows IOException

public longpublic long skip(long n) throwsthrows IOException

public intpublic int available() throwsthrows IOException

public voidpublic void close() throwsthrows IOException

public synchronized voidpublic synchronized void mark(int readlimit) throwsthrows IOException

public synchronized voidpublic synchronized void reset() throwsthrows IOException

public Booleanpublic Boolean markSupported()

164

Introduction to Java

Typical code to open a file InputStream InSt = null; try try { InSt = newnew FileInputStream(“file.txt”); } catchcatch (FileNotFound e) … catchcatch (IOException e)...

165

Introduction to Java Typical code to read a character data

from a filetrytry{ c = InSt.read();}catchcatch (IOException e) { System.out.println(e);}

166

Introduction to Java OutputStream

– Abstract class for output streams– Defines basic methods that must defined

by subclasses– Java like for InputStream provides several

subclasses for OutputStream as well

167

Introduction to Java

Important methods in the OutputStreampublic abstract voidpublic abstract void write(int b) throwsthrows

IOException

public void public void write(byte b[]) throwsthrows IOException

public voidpublic void write(byte b[], int off, int len) throwsthrows IOException

public voidpublic void flush() throws throws IOException

public voidpublic void close() throwsthrows IOException

168

Introduction to Java

Typical code to open a file for outputOutputStream OutSt = null;

trytry

{

OutSt = new new FileOutputStream(“file.txt”);

}

catchcatch (IOException e)

… handle exception

}

169

Introduction to Java Typical code to write data out to a file

trytry

{

OutSt.write()

}

catchcatch (IOException e)

… handle Exception

}

170

Introduction to Java Other Input/Output Classes

– File– ByteArrayInputStream & the Output one– StringBufferInputStream– FilterInputStream & FilterOutputStream– BufferedInputStream &

BufferedOutputStream– DataInputStream & DataOutputStream

171

Introduction to Java More

– PipedInputStream & PipedOutputStream– SequenceInputStream– LineNumberInputStream– PushbackInputStream– PrintStream– RandomAccessFile

172

Introduction to Java And Two Interfaces

– DataInput– DataOutput

173

Introduction to Java The File Class

– The file class provides a platform neutral way to describe files and directories

– The file class defines several staticstatic methods to let you construct files/ directories name compatible with the client/ server platform

– The file class let you check if the file exists/ readable/ writable …

174

Introduction to Java Some constants from the File class

public static final charpublic static final char separatorChar;

public static finalpublic static final String separator;

public static final charpublic static final char pathSeparatorChar;

public static finalpublic static final String pathSeparator;

175

Introduction to Java ByteArrayInputStreamByteArrayInputStream / Output

– This class allows application to handle arrays of bytes as files.

– ByteArrayXXXStream classes redefines some of the methods EX:

• available()available() always returns bytes not read.• reset()reset() reset to the beginning of the array.

StringBufferInputStreamStringBufferInputStream / Output– same as ByteArray it uses a String object instead

176

Introduction to Java FilterInputStream / FilterOutputStream

– This class is used to define a chain of filters

– Each filter will optionally performs some processing on the data and sends it to the next filter in the chain and so on until it reaches the file stream

177

Introduction to Java InputStream

Filter#1

Filter#2

Filter#3

178

Introduction to Java BufferdInputStream / OutputBufferdInputStream / Output

– As the name indicates this class reads/ write data to a buffer a prior.

– Programmers can specify the size of the buffer

– Subsequent activities will be statisfied from the buffer if it contains the requested information.

179

Introduction to Java DataInputStream/ DataOutputStreamDataInputStream/ DataOutputStream

– All previous classes processed data as a stream of bytes this pair of classes allows the programmer to read data directly into Java basic data types such as Boolean, Integers, Floating point numbers, etc.

– This pair extends the Filter classes and provide an implementation for the Data intefaces

180

Introduction to Java LineNumberInputStreamLineNumberInputStream

– This class is an input stream filter that provides the added functionality of keeping track of the current line number.

PipedInputStream / PipedOutputStreamPipedInputStream / PipedOutputStream– Allows two threads to communicate by one

producing the data and write it using output pipe, while the other threads consumes it by reading it first using and input pipe.

181

Introduction to Java SequenceInputStreamSequenceInputStream

– It provides a framework to combine two separate InputStream(s) into one logical InputStream.

– Once the EOF on the first stream is reached the stream continues on the next Stream.

182

Introduction to Java PushbackInputStreamPushbackInputStream

– Allows the user to push back a character to the input stream by using the unread() method.

– Using read() and unread() allows the programmer to take a peak (lookahead) into the input stream.

183

Introduction to Java PrintStreamPrintStream

– allows the Java programmer to write out data to console or files in a human readable format.

– System.out is a PrintStream predefine in Java.

184

Introduction to Java RandomAccessFileRandomAccessFile

– This class extends Object– This class enables programmers to read

and write bytes, text, Java data types to any location in a file.

– This class provides implementation for both the DataInput and the DataOutput interfaces.

185

Java Additional Slides

186

Object-Oriented Programming How Old is Object-Oriented?

– SIMULA 1960s– Smalltalk-80 late 1970s– Most Popular - C++– New (relatively) - Java

187

Object-Oriented Programming What Does It Mean to Be Object-

Oriented?– Identity– Abstraction– Encapsulation (Information Hiding)– Inheritance– Polymorphism– Event Driven

188

Object-Oriented Programming Definition (Grady Booch)

– “Object-Oriented Programming is a method of implementation in which programs are organized as cooperative collections of ObjectsObjects, each of which represents an instance of some ClassClass, and whose classes are all members of hierarchy of classes united via inheritance inheritance relationshipsrelationships”

189

Object-Oriented Programming What’s an Object?

– Attributes(Properties)– Behavior (Operations/Methods/Messages)– State (Rules and Constraints on Attribute

to Control Behavior). What’s an Object Identity?

– Two similar objects have separate Identity, behave separately, change state independently.

190

Object-Oriented Programming What’s a Class (Abstraction)

– Collection of Objects.– Objects in the Class share common

semantics.– Objects in the Class share common

attributes.– Objects behave similarly under similar

conditions.

191

Object-Oriented Programming What’s Abstraction?

– Is one of the fundamental ways we cope with complexity.

– Recognize Similarities.– Ignore Differences.– Similarities & Differences are relative to the

perspective of the observer.

192

Object-Oriented ProgrammingWhat’s Encapsulation? Information Hiding

– Implementers of objects concern themselves with the details of the abstraction.

– Users of objects should only see what’s relevant to use the object.

– Need not know implementation details.

193

Object-Oriented Programming What’s Inheritance?

– Do implementers need to start from scratch when designing new classes? No.

– Inheritance is the concept of (re)using an existing abstraction(s) and expanding upon them or modifying behavior.

– Inheritance from multiple classes is defined as Multiple-InheritanceMultiple-Inheritance.

Inheritances Defines an “Is-A” relationships Among Classes.

194

Object-Oriented Programming

What’s Polymorphism?– “Poly-Morph” - Many forms.– SimilarSimilar Objects/Classes can exhibit same

behavior under different stimuli.– DifferentDifferent Objects/Classes can exhibit

different behavior under same stimuli.– Polymorphism is an abstraction of

behavior.

195

Object-Oriented Programming

What’s Abstract Classes?– As Level of abstraction increases, Generic

definition for certain known behaviors cannot be defined (implemented).

– Classes with one or more unimplemented behavior are called Abstract ClassesAbstract Classes.

– Mathematically speaking Abstract Classes are empty classes - no objects can be instantiated.

196

Introduction to Java Three types of JAVA programs

– Programs with the packagepackage statement as the first line of code defines a package

• PackagePackage Package_name Package_name

– Programs without the package reserved word are either:• Java program code (Default Package)• Application.

197

Introduction to Java

An application could run in either mode if it is constructed as follows.classclass myclass extendsextends java.applet.Applet {

public static voidpublic static void main() {

myclass A = new myclass();

A.init();

A.start();

} …

}

198

Introduction to Java Built-in data types - characters & stringscharacters & strings

– char = 16-bit unsigned, Unicode.• Non-printable characters are presented asnewline \n \u000A backslash \\ \u005C

CR \r \u000D single quote \’ \u0027

Tab \t \u0009 double quote \” \u0022

backspace \b \u0008 any char (octal) \ddd

form feed \f \u000C any Unicode (hex) \udddd