1 Introduction to Object-Oriented Programming and Java.

198
1 Introduction to Object-Oriented Programming and Java

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

Page 1: 1 Introduction to Object-Oriented Programming and Java.

1

Introduction to Object-Oriented Programming and Java

Page 2: 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.

Page 3: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 4: 1 Introduction to Object-Oriented Programming and Java.

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

Page 5: 1 Introduction to Object-Oriented Programming and Java.

5

Java 2 Swing - new features for creating a

graphical user interface Improvements to audio features Drag and drop

Page 6: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 7: 1 Introduction to Object-Oriented Programming and Java.

7

Introduction to Java Java Overview

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

class and object libraries (packages).

Page 8: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 9: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 10: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 11: 1 Introduction to Object-Oriented Programming and Java.

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

Page 12: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 13: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 14: 1 Introduction to Object-Oriented Programming and Java.

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

Page 15: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 16: 1 Introduction to Object-Oriented Programming and Java.

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;

}

Page 17: 1 Introduction to Object-Oriented Programming and Java.

17

Introduction to Java <class_qualifier> is one of the following

reserved keywords– publicpublic– privateprivate– abstractabstract– finalfinal

Page 18: 1 Introduction to Object-Oriented Programming and Java.

18

Introduction to Java What’s in the class body?

– Data members– Methods/messages that operate on the

data.

Page 19: 1 Introduction to Object-Oriented Programming and Java.

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

Page 20: 1 Introduction to Object-Oriented Programming and Java.

20

Introduction to Java Methods/Messages Syntax:

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

{

method_body

}

Page 21: 1 Introduction to Object-Oriented Programming and Java.

21

Java Methods <access_qualifier>

– public privatepublic private– protected abstractprotected abstract– finalfinal

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

Page 22: 1 Introduction to Object-Oriented Programming and Java.

22

Introduction to Java Application are either:

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

Page 23: 1 Introduction to Object-Oriented Programming and Java.

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

Page 24: 1 Introduction to Object-Oriented Programming and Java.

24

Introduction to Java

Example:classclass HelloWorld {

… methods and members

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

// method body

}

… more methods

}

Page 25: 1 Introduction to Object-Oriented Programming and Java.

25

Introduction to Java Simple Stand-alone application

class HelloWorld {

public static void mainmain(String Args[]) {

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

}

}

Page 26: 1 Introduction to Object-Oriented Programming and Java.

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)

Page 27: 1 Introduction to Object-Oriented Programming and Java.

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

Page 28: 1 Introduction to Object-Oriented Programming and Java.

28

Introduction to Java

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

• Expression• Block• Assignment• Flow Control

– Classes

Page 29: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 30: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 31: 1 Introduction to Object-Oriented Programming and Java.

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”

Page 32: 1 Introduction to Object-Oriented Programming and Java.

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)

Page 33: 1 Introduction to Object-Oriented Programming and Java.

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

Page 34: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 35: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 36: 1 Introduction to Object-Oriented Programming and Java.

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

Page 37: 1 Introduction to Object-Oriented Programming and Java.

37

Introduction to Java Expressions

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

level.

Page 38: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 39: 1 Introduction to Object-Oriented Programming and Java.

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

Page 40: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 41: 1 Introduction to Object-Oriented Programming and Java.

41

Introduction to Java

True FalseBoolean Expression

JavaStatements

JavaStatements

If-then-else

Page 42: 1 Introduction to Object-Oriented Programming and Java.

42

Introduction to Java

True

False

Boolean Expression

JavaStatements

If-then

Page 43: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 44: 1 Introduction to Object-Oriented Programming and Java.

44

Introduction to Java

Eval. switch

C1?

C2?

C3?

True

Fal

se

Page 45: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 46: 1 Introduction to Object-Oriented Programming and Java.

46

Introduction to Java Control Flow (repetition)

– whilewhile (BooleanExpression)statement-block

– dodo statement-block whilewhile (booleanExpression)

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

Page 47: 1 Introduction to Object-Oriented Programming and Java.

47

Introduction to Java

Ex?

Fal

seT

rue

While-stmt

Page 48: 1 Introduction to Object-Oriented Programming and Java.

48

Introduction to Java

Ex?False

Tru

e

Page 49: 1 Introduction to Object-Oriented Programming and Java.

49

Introduction to Java

Eval I

Is I?

Inc.

Page 50: 1 Introduction to Object-Oriented Programming and Java.

50

Introduction to Java Classes - definition

[<modifiers>] classclass <classname> {

class_methods and Data …

} <Modifiers>

– publicpublic - protectedprotected -abstractabstract– privateprivate - finalfinal

Page 51: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 52: 1 Introduction to Object-Oriented Programming and Java.

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

Page 53: 1 Introduction to Object-Oriented Programming and Java.

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

Page 54: 1 Introduction to Object-Oriented Programming and Java.

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

Page 55: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 56: 1 Introduction to Object-Oriented Programming and Java.

56

Introduction to Java

C1

C2

A C

lass

Page 57: 1 Introduction to Object-Oriented Programming and Java.

57

Introduction to Java How do we create two separate

objects?C1 = newnew MyClass();

C2 = newnew MyClass();

Page 58: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 59: 1 Introduction to Object-Oriented Programming and Java.

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

Page 60: 1 Introduction to Object-Oriented Programming and Java.

60

Introduction to Java Type Wrapper Classes - Distinguish?

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

Page 61: 1 Introduction to Object-Oriented Programming and Java.

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

Page 62: 1 Introduction to Object-Oriented Programming and Java.

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) { … }

….

}

Page 63: 1 Introduction to Object-Oriented Programming and Java.

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

Page 64: 1 Introduction to Object-Oriented Programming and Java.

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

Page 65: 1 Introduction to Object-Oriented Programming and Java.

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

Page 66: 1 Introduction to Object-Oriented Programming and Java.

66

Introduction to Java Is that All? Definitely Not

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

• On-line Documentation

Page 67: 1 Introduction to Object-Oriented Programming and Java.

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

Page 68: 1 Introduction to Object-Oriented Programming and Java.

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

Page 69: 1 Introduction to Object-Oriented Programming and Java.

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

Page 70: 1 Introduction to Object-Oriented Programming and Java.

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

Page 71: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 72: 1 Introduction to Object-Oriented Programming and Java.

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

Page 73: 1 Introduction to Object-Oriented Programming and Java.

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

Page 74: 1 Introduction to Object-Oriented Programming and Java.

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’ };

Page 75: 1 Introduction to Object-Oriented Programming and Java.

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

Page 76: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 77: 1 Introduction to Object-Oriented Programming and Java.

77

Introduction to Java Multi-dimensional arrays

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

Page 78: 1 Introduction to Object-Oriented Programming and Java.

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

Page 79: 1 Introduction to Object-Oriented Programming and Java.

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

Page 80: 1 Introduction to Object-Oriented Programming and Java.

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

Page 81: 1 Introduction to Object-Oriented Programming and Java.

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

Page 82: 1 Introduction to Object-Oriented Programming and Java.

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?

Page 83: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 84: 1 Introduction to Object-Oriented Programming and Java.

84

Introduction to Java

Scope

Class

{ }

Outermost Scope

{

}

{

}

{}

{}

Page 85: 1 Introduction to Object-Oriented Programming and Java.

85

Introduction to Java (2)

Page 86: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 87: 1 Introduction to Object-Oriented Programming and 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

}

Page 88: 1 Introduction to Object-Oriented Programming and Java.

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)

Page 89: 1 Introduction to Object-Oriented Programming and Java.

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.

}

Page 90: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 91: 1 Introduction to Object-Oriented Programming and Java.

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

Page 92: 1 Introduction to Object-Oriented Programming and Java.

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

Page 93: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 94: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 95: 1 Introduction to Object-Oriented Programming and Java.

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

Page 96: 1 Introduction to Object-Oriented Programming and Java.

96

Introduction to Java (3)

Page 97: 1 Introduction to Object-Oriented Programming and Java.

97

Introduction to Java Structure of a JAVA Program.

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

Page 98: 1 Introduction to Object-Oriented Programming and Java.

98

Introduction to Java JAVA Packages

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

Page 99: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 100: 1 Introduction to Object-Oriented Programming and Java.

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)

Page 101: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 102: 1 Introduction to Object-Oriented Programming and Java.

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

Page 103: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 104: 1 Introduction to Object-Oriented Programming and Java.

104

Introduction to Java Java.net

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

Page 105: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 106: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 107: 1 Introduction to Object-Oriented Programming and Java.

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

Page 108: 1 Introduction to Object-Oriented Programming and Java.

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

Page 109: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 110: 1 Introduction to Object-Oriented Programming and Java.

110

Introduction to Java

Object

Container

Panel

Applet

Component

Page 111: 1 Introduction to Object-Oriented Programming and Java.

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

Page 112: 1 Introduction to Object-Oriented Programming and Java.

112

Introduction to Java Creating Applets

– Derive from java.applet.Applet

Ex:

public classpublic class MyFirstApplet extendsextends java.applet.Applet {

… // Applet Code

}

Page 113: 1 Introduction to Object-Oriented Programming and Java.

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)

Page 114: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 115: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 116: 1 Introduction to Object-Oriented Programming and Java.

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

Page 117: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 118: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 119: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 120: 1 Introduction to Object-Oriented Programming and Java.

120

Introduction to Java Simple Appletpublic class HelloWorld extends Applet {

public void init() {

resize(500,500); // pixels.

}

// public void start() use default from parent

Page 121: 1 Introduction to Object-Oriented Programming and Java.

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

}

}

Page 122: 1 Introduction to Object-Oriented Programming and Java.

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>

Page 123: 1 Introduction to Object-Oriented Programming and Java.

123

Introduction to Java More HTML Tags

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

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

browser.

Page 124: 1 Introduction to Object-Oriented Programming and Java.

124

Introduction to Java The Graphics g object

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

Page 125: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 126: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 127: 1 Introduction to Object-Oriented Programming and Java.

127

Introduction to Java Example - HTML Param Tags

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

<param COLOR=“red”>

<param SIZE=“36”>

</applet>

Page 128: 1 Introduction to Object-Oriented Programming and Java.

128

Introduction to Java Example - applet init() code

String color;

String size;

color = getParameter(“COLOR”);

size = getParameter(“SIZE”);

Page 129: 1 Introduction to Object-Oriented Programming and Java.

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

Page 130: 1 Introduction to Object-Oriented Programming and Java.

130

Introduction to Java

(0,0)x

y

(20)

(10)

Page 131: 1 Introduction to Object-Oriented Programming and Java.

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

Page 132: 1 Introduction to Object-Oriented Programming and Java.

132

Introduction to JavaH

eig

ht

Width

Page 133: 1 Introduction to Object-Oriented Programming and Java.

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

Page 134: 1 Introduction to Object-Oriented Programming and Java.

134

Introduction to Java

(0,0)

90

180

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

Page 135: 1 Introduction to Object-Oriented Programming and Java.

135

Introduction to Java Draw Polygons

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

Page 136: 1 Introduction to Object-Oriented Programming and Java.

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

Page 137: 1 Introduction to Object-Oriented Programming and Java.

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

Page 138: 1 Introduction to Object-Oriented Programming and Java.

138

Introduction to Java

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

(5,5)

(25,15)

1510

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

Page 139: 1 Introduction to Object-Oriented Programming and Java.

139

Introduction to Java Applets and Fonts Information

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

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

Page 140: 1 Introduction to Object-Oriented Programming and Java.

140

Introduction to Java

Graphics

Java

Baseline

Lea

din

g

Ascent

Descent

Height = Leading+Ascent+Descent

Page 141: 1 Introduction to Object-Oriented Programming and Java.

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

Page 142: 1 Introduction to Object-Oriented Programming and Java.

142

Introduction to Java

Th1

Th2

Tim

e

Main ThreadThread 1

Thread 2

Page 143: 1 Introduction to Object-Oriented Programming and Java.

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

Page 144: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 145: 1 Introduction to Object-Oriented Programming and Java.

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

Page 146: 1 Introduction to Object-Oriented Programming and Java.

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

Page 147: 1 Introduction to Object-Oriented Programming and Java.

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

Page 148: 1 Introduction to Object-Oriented Programming and Java.

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

Page 149: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 150: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 151: 1 Introduction to Object-Oriented Programming and Java.

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

Page 152: 1 Introduction to Object-Oriented Programming and Java.

152

Introduction to Java (4)

Page 153: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 154: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 155: 1 Introduction to Object-Oriented Programming and Java.

155

Introduction to Java

Object

Throwable

Error Exception

Page 156: 1 Introduction to Object-Oriented Programming and Java.

156

Introduction to Java Exceptions and Errors

– Java Language defines plenty of Error and Exception objects

Page 157: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 158: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 159: 1 Introduction to Object-Oriented Programming and Java.

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}

Page 160: 1 Introduction to Object-Oriented Programming and Java.

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

Page 161: 1 Introduction to Object-Oriented Programming and Java.

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

Page 162: 1 Introduction to Object-Oriented Programming and Java.

162

Introduction to Java

Object

RandomAccessFileOutputStreamInputStream

Page 163: 1 Introduction to Object-Oriented Programming and Java.

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

Page 164: 1 Introduction to Object-Oriented Programming and Java.

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

Page 165: 1 Introduction to Object-Oriented Programming and Java.

165

Introduction to Java Typical code to read a character data

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

Page 166: 1 Introduction to Object-Oriented Programming and Java.

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

Page 167: 1 Introduction to Object-Oriented Programming and Java.

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

Page 168: 1 Introduction to Object-Oriented Programming and Java.

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

}

Page 169: 1 Introduction to Object-Oriented Programming and Java.

169

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

trytry

{

OutSt.write()

}

catchcatch (IOException e)

… handle Exception

}

Page 170: 1 Introduction to Object-Oriented Programming and Java.

170

Introduction to Java Other Input/Output Classes

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

BufferedOutputStream– DataInputStream & DataOutputStream

Page 171: 1 Introduction to Object-Oriented Programming and Java.

171

Introduction to Java More

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

Page 172: 1 Introduction to Object-Oriented Programming and Java.

172

Introduction to Java And Two Interfaces

– DataInput– DataOutput

Page 173: 1 Introduction to Object-Oriented Programming and Java.

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 …

Page 174: 1 Introduction to Object-Oriented Programming and Java.

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;

Page 175: 1 Introduction to Object-Oriented Programming and Java.

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

Page 176: 1 Introduction to Object-Oriented Programming and Java.

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

Page 177: 1 Introduction to Object-Oriented Programming and Java.

177

Introduction to Java InputStream

Filter#1

Filter#2

Filter#3

Page 178: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 179: 1 Introduction to Object-Oriented Programming and Java.

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

Page 180: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 181: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 182: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 183: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 184: 1 Introduction to Object-Oriented Programming and 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.

Page 185: 1 Introduction to Object-Oriented Programming and Java.

185

Java Additional Slides

Page 186: 1 Introduction to Object-Oriented Programming and Java.

186

Object-Oriented Programming How Old is Object-Oriented?

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

Page 187: 1 Introduction to Object-Oriented Programming and Java.

187

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

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

Page 188: 1 Introduction to Object-Oriented Programming and Java.

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”

Page 189: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 190: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 191: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 192: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 193: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 194: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 195: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 196: 1 Introduction to Object-Oriented Programming and Java.

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.

Page 197: 1 Introduction to Object-Oriented Programming and Java.

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

} …

}

Page 198: 1 Introduction to Object-Oriented Programming and Java.

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