23
1 Advanced System Design Using Java Technology Nasreddine Aoumeur E-mail: [email protected] Home page: http://www.cs.le.ac.uk/~na80 /LABS Prof. Jose Fiadeiro : Advanced System Design with JAVA A Brief History January 1996: first official release JDK 1.0 n Web: applets, security, URL, networking n GUI: Abstract Windows Toolkit (AWT) February 1997: JDK 1.1 n Authentication: digital signatures, certificates n Distributed computing: RMI, object serialization, Java IDL/CORBA n Database connectivity: JDBC n Component architecture: JavaBean A Brief History (continued) December 1998: Java 2 Platform (JDK 1.2): n Standard (J2SE), Enterprise (J2EE), and Micro (J2ME) Editions n JFC: Swing, Java2D, Java3D n Java Cryptography Extension (JCE) n Enterprise computing: enterprise JavaBean (EJB), servlets, Java server page (JSP), Jini, XML n Java Multimedia Framework (JMF) n Embedded systems: KVM, JavaCard n Performance enhancement: JIT, HotSpot VM A Brief History (cont’d) May 2000: J2SDK v1.3 n Enhancements in features, performance, and security. May 2001: J2SDK v1.4 beta n XML, XSLT, JCE, etc. all included in J2SE n Numerous enhancements: I/O, assertions, regular expression, logging, etc. 2002: J2SDK v1.4.1 n Generic types Overwhelming Alphabet soup Characteristics of Java Simple Object-oriented Statically typed Compiled Architecture neutral Garbage collected Multi-threaded Robust Secure Extensible

Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

1

Advanced System Design UsingJava Technology

Nasreddine Aoumeur

E-mail: [email protected] page: http://www.cs.le.ac.uk/~na80/LABS

Prof. Jose Fiadeiro : AdvancedSystem Design with JAVA

A Brief HistoryJanuary 1996: first official release JDK 1.0

n Web: applets, security, URL, networkingn GUI: Abstract Windows Toolkit (AWT)

February 1997: JDK 1.1n Authentication: digital signatures, certificatesn Distributed computing: RMI, object serialization,! Java

IDL/CORBAn Database connectivity: JDBCn Component architecture: JavaBean

A Brief History (continued)December 1998: Java 2 Platform (JDK 1.2):

n Standard (J2SE), Enterprise (J2EE), and Micro (J2ME)Editions

n JFC: Swing, Java2D, Java3Dn Java Cryptography Extension (JCE)n Enterprise computing: enterprise JavaBean (EJB),!

servlets, Java server page (JSP), Jini, XMLn Java Multimedia Framework! (JMF)n Embedded systems: KVM, JavaCardn Performance enhancement: JIT, HotSpot VM

A Brief History (cont’d)May 2000: J2SDK v1.3

n Enhancements in features, performance, and security.May 2001: J2SDK v1.4 beta

n XML, XSLT, JCE, etc. all included in J2SEn Numerous enhancements: I/O, assertions, regular

expression, logging, etc.2002: J2SDK v1.4.1

n Generic types

Overwhelming Alphabet soup Characteristics of JavaSimpleObject-orientedStatically typedCompiledArchitecture neutral

Garbage collectedMulti-threadedRobustSecureExtensible

Page 2: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

2

Your First Java Program/* * Example HelloWorld * Prints the message "Hello, World!“ */public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, world.”); }}

Packages

Java provides mechanisms to organizelarge-scale programs in a logical andmaintainable fashion.n Class --- highly cohesive functionalitiesn File --- one class or more closely related

classesn Package --- a collection of related classes or

packages

Java Class Library

The Java class library is organized into anumber of packages:n java.lang --- generaln java.awt --- GUIn java.io --- I/On java.util --- utilitiesn java.applet --- appletn java.net --- networking

Another Example// Example Time// Prints a greeting message with // the current time. import java.util.*; public class Time {

public static void main(String[] args) { System.out.println("Hello!”); System.out.println("The time is " + new Date()); }

}

Java Keywords

while

voidtrythrowsthrowthis

synchronisedswitchsuperstaticshort

returnpublicprotectedprivatepackage

nullnewnativelonginterface

intinstanceofimportimplementsif

gotoforfloatfinallyfinal

extendselsedoubledodefault

continueclasscharcatch

casebytebreakbooleanabstract Data TypesType

byteshortintlong

float

double

Storage

8 bits16 bits32 bits64 bits

32 bits

64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits

Max Value

12732,7672,147,483,647> 9 x 1018

Page 3: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

3

Boolean Type

booleanBoolean constants:

truefalse

Integer TypesintbyteShort longExamples of integer constants:

354 -37 0 246543

Floating Point Type

DoublefloatExamples of floating point constants:

4.642 -0.034 5.98e24 9.11e-31

Character Typechar16-bit Unicode character.ASCII is a subset of Unicode --- ISO-8859 (Latin-1)Examples of character constants:'A''y''8''*'' ' (space)'\n' (new line).

Escape Sequences

\b! backspace\f! form feed\n! new line (line feed)\r! carriage return\t! tab\"! double quote\'! single quote\\! backslash\uhhhh: hex-decimal code, e.g. \u000A\ddd: octal code, e.g. \040

StringExamples of string literals:"watermelon""fig""$%&*^%!!""354"" " (space)"" (empty string)constructoroperator + and +=methods:

n charAt(int i)n length()

Page 4: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

4

Arithmetic Operators andExpressions

+ addition- subtraction* multiplication/ division% remainderprecedence and association

Example Time2import java.util.*; public class Time2 { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.println("Hello!"); System.out.println("The time is " + hour / 10 + hour % 10 + ":" + minute / 10 + minute % 10 + ":" + second / 10 + second % 10); } }

Variable declaration andinitializationint x, y, z; long count; char a, b; boolean flag; float massInKilos;

short timeInSeconds = 245; char ch1 = 'K', ch2 = '$'; boolean isNew = true; double maxVal = 35.875;

Assignmentstotal = quantity * unitPrice; count = count + 1; count += 1; count++;

Postfix/Prefix Operators

! x!(before) expr x(after)Postfix increment x++ 1 1 2Postfix decrement x— 1 1 0Prefix increment ++x 1 2 2Prefix decrement --x 1 0 0

Flow control

It is like C/C++:

if/else

do/while

for

switch

if(x==4) { // act1} else { // act2}

int i=5;do { // act1 i--;} while(i!=0);

int j;for(int i=0;i<=9;i++) { j+=i;}

char c=IN.getChar();switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2}

Page 5: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

5

SequenceA sequence of statements are executedsequencially.

S1; S2; ...; Sn;Example:temp = x*x + y*y;d = Math.sqrt(temp);

x = 5;y = 11;z = x + y;System.out.println(z);

Conditional Expression

condition ? exp1 : exp2

Example: (x >= 0) ? x : -x

(a >= b) ? a : b

BlockA block consists of a sequence of statements orlocal variable declarations enclosed by { and }

{ S1; S2; ...; Sn; }Example:{ double temp, d; temp = x*x + y*y; d = Math.sqrt(temp);}

If StatementExecute a block of code (Action) if a condition istrue. The block of code is executed at most once.

if (condition) { statements; }

Example: if (x % 2 == 0) { System.out.println("The number is even."); }

Relational ExpressionUse equality operators or relationaloperators, which all return boolean results.Both operands must be of numerical types.

== equal to!= not equal to< less than> greater than<= less than or equal to>= greater than or equal to

If-Else Statement.if (condition) { statement1;} else { statement2;}

if (condition1) { statement1;} else if (condition2) { statement2;} else if (condition3) { statement3;} else { statement4;}

Page 6: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

6

Logical Expression

!a logical negationa | b logical-ora & b logical-anda || b conditional-ora && b conditional-and

Example: Day2.javaString sDay;if (day == Calendar.SUNDAY) { sDay = "Sunday";} else if (day == Calendar.MONDAY) { sDay = "Monday";} else if (day == Calendar.TUESDAY) { sDay = "Tuesday";} else if (day == Calendar.WEDNESDAY) { sDay = "Wednesday";} else if (day == Calendar.THURSDAY) { sDay = "Thursday";} else if (day == Calendar.FRIDAY) { sDay = "Friday";} else if (day == Calendar.SATURDAY) { sDay = "Saturday";} else { sDay = "Unknown";}

Switch Statement switch (expression) {

case value1:! statement1;! break;case value2:! statement2;! break;case value3:! statement3;! break;default:! statement4;}

Example: Day3.java String sDay; switch (day) { case Calendar.SUNDAY: sDay = "Sunday"; break; case Calendar.MONDAY: sDay = "Monday"; break; case Calendar.TUESDAY: sDay = "Tuesday"; break; case Calendar.WEDNESDAY: sDay = "Wednesday"; break;

case Calendar.THURSDAY: sDay = "Thursday"; break; case Calendar.FRIDAY: sDay = "Friday"; break; case Calendar.SATURDAY: sDay = "Saturday"; break; default: sDay = "Unknown"; }

While LoopRepeat a block of code while a condition is true.There is no limit to the number oftimes that theblock can be executed.

while (condition) { statements; }

When the body of a while statement, or of a forstatement consists of a single statement, nobraces are necessary.

Examples: While Loopint i = 1; while (i <= 20) { System.out.println(i); i++; }

int i = 20; while (i >= 0) { System.out.println(i); i--; }

Page 7: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

7

For Loop

for (initialization; condition; incrementation) {

! statement;}

Examples: For Loopfor (int i = 1; i <= 20; i++) { System.out.println(i); }

for (int i = 20; i >= 0; i--) { System.out.println(i); }

Do-While Loopdo { ! statements; } while (condition);

Examples: Do-While Loopint i = 1; do { System.out.println(i); i++; } while (i <= 20)

int i = 20; do { System.out.println(i); i--; } while (i >= 0);

Break and Continue

A break statement in a loop terminates theloop.A continue statement in a loop terminatesthe current iteration of the loop, andcontinue with the next iteration of the loop.

Examples: Break and Continueint i = 0; while (i <= 20) { i++; if (i % 5 == 0) break; System.out.println(i); }

int i = 0; while (i <= 20) { i++; if (i % 5 == 0) continue; System.out.println(i); }

Page 8: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

8

StringsStrings are objects of class StringString name;String lecName = “Gillian Miller”;

String name1 = “Joan”;String name2 = “JOAN”;String name3 = “ xyz “;if (name1.equals (name2)) …..if (name1.equalsIgnoreCase (name2)) ..

int j = name3.trim().length();

n “Hello” is shortcut for new String(“Hello”)n Strings are immutable - many string methods create new stringsn Strings start from char 0 lecName.substring(0,4) is “Gill”

String methodsequals (String val)length()charAt( int pos)trim()toLowerCase()toUpperCase()substring(int from, int len);

ArraysArrays are collections of a series of values of thesame type (a primitive type or an object type)Arrays are Java objects - they have a reference

access using arrayname[index]indexing from 0 to size - 1

type arrayname[] = new type [size];

type[] arrayname;

arrayname = new type[size];

String myFriends[] = {“bob”, “carol”, “ ted” , alice”};for (int j=o; j<myFriends.length(); j++) System.out.println (“friend “ + myFriends[j]);

Arrays - ExamplesArrays - Examples

int myInts [] = new int [100];for (int j=o; j<100; j++) myInts [j] = j;

Car myCars [ ] = new Car [3];myCars [0] = new Car (“holden”, “yellow”);myCars [1] = new Car (“ford”, “green”);myCars [2] = new Car (“honda”, “blue”);for (int j=0; j<3; j++) System.out.println(“car “ + j + car[j].toString);

Arrays - ExamplesArrays - Examplesclass Minimum { public static void main (String args[]) { int[] my_array = {45,12,1,13,-4,0,-23,1001}; int minimum, i;

minimum=my_array[0]; for (i=0; i<my_array.length; i=i+1) if (my_array[i]<minimum) minimum=my_array[i];

System.out.print(„The min number is "); System.out.println(minimum);

}}

Result:

The Minimumis -4

Some applicationsEx1 : Write a JAVA program that enters any integers

computes the sum of positive one and the number ofnegative ones, and it stops either after entering 30numbers or after entering the integer –20.

Ex2 : Compute the max, min of these numbers.Ex3 : print the following numbers 6, 10, 18 in letters if

entered, and do not consider them while computing thesum, max, and min.

Ex4 : do the same with an array of (thirty) numbers.

Some applications

Ex : Write Java program that depending on an enteredcharacter (`r´ for rectangle, `t´ for triangle, and `c´ forcircle), it computes the area and perimeter of such figures.All dimensions are supposed to be double. Try to havejust one procedure (method) for reading the elements.

Page 9: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

9

Reading from keyboard import javax.swing.* System.out.println(„Enter your number"); String s =

JOptionPane.showInputDialog(„Enterednumber:");

double d = Double.valueOf(s).doubleValue(); int n = Integer.valueOf(s).intValue(); float f = Float.valueOf(s).floatValue();

Advanced System Design UsingJava Technology : OO concepts

Nasreddine Aoumeur

E-mail: [email protected] page: http://www.cs.le.ac.uk/~na80

Objects and ClassesIn real world terms:

An object represents an individual entity or thing.A class represents a group of objects that exhibit somecommon characteristics or behavior.Classes are resulted from classification.Examples of classes in real world:

n Studentsn Graduate studentsn Undergraduate studentsn MS studentsn Ph.D. students

Basic Concepts of OOAn object has

n state: defined by the set of fields or attributes.n behavior: defined by the set of methods or operation

that can be applied to the object.n identity: determined at the creation time.

Classn A template for creating objects.n Objects of the same class exhibit the same behavior.

They may have different states.

Objects and ClassesObjects and Classes

Representation like in real world:

The door

one can

• high = 2.0 m• width = 0.7 m• ....

Object

has

Attributs (state)

Methods(behaviour)

• open• clsoe• block• .....

Objects and ClassesIn programming terms:

A class defines a self-contained software component that represents a realworld class.The design of classes should follows the basic principles of object-orientation:

n modularityn encapsulation

Each object is an instance of its class.A class defines the common characteristics of its instances:

n the behaviors andn the templates of the fields.

Each object has its own state, i.e., the values of the fields.

Page 10: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

10

OBJECT AND CLASS

The class MyDate The object d is an instance of class MyDateMyDate d:MyDate fieldsday (or:,variables day = 31month state month = 1year data members) year = 2000

set (d,m,y) set (d,m,y)incDays (nDays) methods incDays (nDays)getWeekDay ( ) getWeekDay ()

OO and JavaJava is pure OO language

n C++ is a procedural language with OO conceptsAll JAVA programs consist of objects (data andbehaviour) which “interact” with each other bycalling instance methods All data is stored withinobjects which are instances of a classThere are no “global” variables or methodsThere are no low level pointers (only referencesto objects)

Java Class Templatepublic class Classname {// attributes - basic types and other object types

eg private int length;private String name;private MyClass myObject;

// optionally one or more constructorspublic classname () { …. };public classname (parm1, parm2) {….};

// optionally one or more methodspublic rettype procname (args );private rettype procname ();

In most cases a main programpublic static void main (String args[]) { }

}

public class Car {private String make, carColor;private int id;private static int idCount = 0;

// constructorpublic Car (String pmake, String pcol) {

make = pmake;carColor = pcol;id = ++idCount;

}

public void changeColor (String newColor) {carColor = newColor; }

public int getId () { return id };

public String toString() {return “Car “ + id + “ “ + “ “ + make + “ “ + carColor; }

}

Using ObjectsCar car1, car2;car1 = new Car (“holden”, “red”);car2 = new Car (“ford”, “yellow” );System.out.println (“car1 “ + car1.toString ());System.out.println (“car2” + car2.toString ());

Declarations of variable of object typesUse new to create instances of objects of that classnew invokes the constructor of that objectTo call method use reference with a “.” then method name.car2.changeColor(“green”);

private String makeprivate String colorprivate int idprivate static int idCount;

public Car (String m, String c)public String toString()

public class Car

Car

id = 1make = “holden”color = “red”

Car

id = 2make = “ford”color = “yellow”

idCount = 2

new Car()

new Car( )

Page 11: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

11

Object InstancesEach object stores its own attributes.

however a static attribute exists once for each class.

we also use final to denote constants

static methods may be invoked without an object notethe static in main

Object References continued

Car car3;car3.SetColor (“green”);

Car carA, carB;carA = new Car (“holden”, “red”);carB = new Car (“ford”, “yellow”);carA = carB;carB.changeColor (“green”);System.out.println (“carA “ + carA.toString());

What is wrong with this ?

StaticMember data - Same data is used for all theinstances (objects) of some Class.

class A { public static int x_ = 1;};

A a = new A();A b = new A();System.out.println(b.x_); ?a.x_ = 5;System.out.println(b.x_); ?A.x_ = 10;System.out.println(b.x_); ?

Assignment performed on the first access to theClass.Only one instance of ‘x’exists in memory

Scope of attributesInstance variables and methods are visibile within that object and otherinstances of the class.With respect to other objects and classes scope can be modified

n private : accessible only within the concerned classn protected : could be changed at subclassesn public : could be manipulated everywhere

Encapsulation PrincipleIn general all attributes should be private. Use methods such as get and setso that other classes can see and change attributes

n use getxxxx() and setxxxx( …)Only methods that are part of the “interface” should be public.

ENCAPSULATION

class MyDate { private int day, month, year; public void set (int d, int m, int y) {day=d, month= m, year= y… } public void incDays (int nDays) {. . .} public int getWeekDay ( ) { . . . }}

class OtherClass { void anyMethod { MyDate d = new MyDate ( ) ; d.set (31, 1, 2000) ; d.month = 2; // COMPILATION ERROR !!! }}

Why Encapsulation?

//without encapsulation:circle k = new circle();k.radius = – 88;// radius negative!

//with encapsulationcircle k = new circle();boolean b = k.setRadius(– 88);// radius never negative!

class circle{double radius, middlepointX, middlepointY;boolean setRadius(double newRadius){

if(newRadius > 0){radius = newRadius;return true;}

else return false;}

}

Page 12: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

12

Class Declaration Syntax

[ ClassModifiers ] class ClassName ! [ extends SuperClass ] ! [ implements Interface1, Interface2! ...] { ! ClassMemberDeclarations }

Class Visibilitypublic : Accessible everywhere. One public class allowedper file. The file must be named ClassName.javadefault : Accessible within the current package.Other class modifiers:

n abstractA class that contains abstract methods. Couldn’t be instantiated

n finalNo subclasses

Field and Method Declaration[ MethodModifiers ] ResultType! Name ( [ ParameterList ]! ) { ! Statements }

[ FieldModifiers ] Type! FieldName1 [ = Initializer1 ] , !! FieldName2 [ = Initializer2 ] ...;

Special Methodspublic boolean equals(Object o)

n o1.equals(o2) versus o1 == o2n The equals() method tests the equality of two objects.n The == operator tests the identity of two objects.n When compare two strings, use s1.equals(s2) instead of s1 ==s2.

public String toString()n returns a string representation of the state of the objectpublic void finalize()

n invoked by the Java runtime just before the object is garbage-collected

Packages

A package physically and logically bundlesa group of classesn Classes are easier to find and use (bundled

together)wA package is an abstraction of classes

n Avoid naming conflictsn Control access to classes

wUnrestricted access between classes of the samepackage

wRestricted access for classes outside the package

Creating a Package

place a package statement at the top ofthe source file in which the class or theinterface is defined.n A default package is implicitly declared

The scope of the packagestatement is the entiresource file. package p1;

public class C1 {...}class C2 {...}

C1.java

Page 13: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

13

Using Package Members

Only public package members are accessibleoutside the package in which they are defined.

n Refer to a member by its long (qualified) namew A qualified name of a class includes the package that contains

the classw Good for one-shot uses

n Import the package memberw When only a few members of a package are used

n Import the entire packagew May lead to name ambiguity

Using Package Members (Cont)

Refer to a package member by its qualifiedname:p1.C1 myObj = new p1.C1();

Importing a package membern Place an import statement at the beginning of

the file, after the package statement:import p1.C1;...C1 myObj = new C1();

Importing an entire packagen Use the import statement with the asterisk (*) wildcard character:

import p1.*;...C1 myObj = new C1();

n Name disambiguationimport p1.*; // contains class C1import p2.*; // contains another C1 class

... C1 myObj = new C1(); // ambiguity error p1.C1 myObj = new p1.C1(); // OK

Using Package Members (Cont) Access controlpublic class

n ‘new’ is allowed from other packages ( default: onlyfrom the same package (note: not necessarily from the samefile) )

package P1;public class C1 {}class C2 {}

package P2; class C3 {}

package P3;import P1.*;import P2.*;

public class DO { void foo() {

C1 c1 = new C1();C2 c2 = new C2(); // ERRORC3 c3 = new C3(); // ERROR

}}

Access Control - cont.

Base

Derived

Package P1

Package P2

SomeClass

prot

ecte

d

public

SomeClass2

private

Friendly

Inheritance

Usage

Relationship among Classes:Inheritance

A mechanism to organize classes by commonalities.n subclasses, specializationn superclass, generalization

Is-a relationExample:

n A graduate student is a student.n A Master student is a graduate student.n A Ph.D. student is a graduate student.n An undergraduate student is a student.

Page 14: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

14

(UML) Class Diagram: InheritanceStudent

GraduateStudent UndergraduateStudent

MasterStudent PhDStudent

Class Declaration Syntax in Java

[ ClassModifiers ] class ClassName ! [ extends SuperClass ] ! [ implements Interface1, Interface2! ...] { ! ClassMemberDeclarations }

Inheritance

Base

Derived

class Base { Base(){} Base(int i) {} protected void foo() {…}}

class Derived extends Base { Derived() {} protected void foo() {…} Derived(int i) { super(i); … super.foo(); }}

As opposed to C++, it is possible to inherit only from ONE class.Pros avoids many potential problems and bugs.Cons might cause code replication

Method OverloadingTwo or more methods/constructors with the samename but different numbers or different types ofparameters:…used mainly in the constructors.

void methodA(int i)void methodA(int i, int j)

void methodB(int i)void methodB(float f)

Avoid overloading

Polymorphism

Inheritance creates an “is a” relation:For example, if B inherits from A, then we say

that “B is kind of an A”.Implications are:n access rights (Java forbids reducing access

rights) - derived class can receive all themessages that the base class can.

n behavior

SUBCLASS AND SUPERCLASS

GuiComponent width:int height:int center:point setOptimalSize( ) moveTo(newX, newY) Scrollbar

Editbox minValue text: String maxValue getValue( )

append(String) setOptimalSize( ) getText( )

Page 15: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

15

SUBCLASSINGq A subclass inherits all members of its superclass:

Ø VariablsØ Methods

q A subclass can:Ø Add more variablesØ Add more methodsØ Override methods of its superclass

Scrollbar sb = new Scrollbar ( ) ; Q: What are the variables of sb? What are the methods that sb can execute?

Inheritance more examples:Book.java

class Book { protected int pages = 1500;

public void pageMessage() { System.out.println("Number of pages: " + pages); }}

Inheritance more examples:Dictionary.java

class Dictionary extends Book { private int definitions = 52500;

public void definitionMessage() { System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); }}

Inheritance more examples:Words.java

class Words { public static void main (String[] args) { Dictionary webster = new Dictionary(); webster.pageMessage(); webster.definitionMessage(); }}

Output:C:\Examples>java WordsNumber of pages: 1500Number of definitions: 52500Definitions per page: 35

Inheritance more examples:Book2.java

class Book2 { protected int pages;

public Book2(int pages) { this.pages = pages; }

public void pageMessage() { System.out.println("Number of pages: " + pages); }}

Inheritance more examples:Dictionary2.java

class Dictionary2 extends Book2 { private int definitions;

public Dictionary2(int pages, int definitions) { super (pages); this.definitions = definitions; }

public void definitionMessage () { System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); }}

Page 16: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

16

Inheritance more examples:Words2.java

class Words2 { public static void main (String[] args) { Dictionary2 webster = new Dictionary2(1500, 52500); webster.pageMessage(); webster.definitionMessage(); }}

Output:C:\Examples>java Words2Number of pages: 1500Number of definitions: 52500Definitions per page: 35

Inheritance more examples:Book3.java

class Book3 { protected String title; protected int pages;

public Book3(String title, int pages) { this.title = title; this.pages = pages; }

public void info() { System.out.println("Title: " + title); System.out.println("Number of pages: " + pages); }}

Inheritance more examples:Dictionary3a.java

class Dictionary3a extends Book3 { private int definitions;

public Dictionary3a(String title, int pages, int definitions) { super (title, pages); this.definitions = definitions; }

public void info() { System.out.println("Dictionary: " + title); System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); }}

Inheritance more examples:Dictionary3b.java

class Dictionary3b extends Book3 { private int definitions;

public Dictionary3b(String title, int pages, int definitions) { super (title, pages); this.definitions = definitions; }

public void info() { super.info(); System.out.println("Number of definitions: " + definitions); System.out.println("Definitions per page: " + definitions/pages); }}

Inheritance more examples:Books.java

class Books { public static void main (String[] args) { Book3 java = new Book3("Introduction to Java", 350); java.info(); System.out.println(); Dictionary3a webster1 = new Dictionary3a("Webster English Dictionary",

1500, 52500); webster1.info(); System.out.println(); Dictionary3b webster2 = new Dictionary3b("Webster English Dictionary",

1500, 52500); webster2.info(); }}

Inheritance more examples:Books.java

Output:C:\Examples>java BooksTitle: Introduction to JavaNumber of pages: 350

Dictionary: Webster English DictionaryNumber of definitions: 52500Definitions per page: 35

Title: Webster English DictionaryNumber of pages: 1500Number of definitions: 52500Definitions per page: 35

Page 17: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

17

Inheritance more examples:Overloading vs. Overriding

Overloadingn More than one methods have the same name but

different signaturesOverriding

n Replacing the implementation of a methods in thesuperclass with one of your own.

n You can only override a method with the samesignature.

n You can only override instance methods.

Abstract ClassAn abstract class is a class with partialimplementation.It implements behaviors that are common to allsubclasses, but defers to the subclasses toimplement others (abstract methods).An abstract class cannot be instantiatedThe subclass of an abstract class must overridethe abstract methods of the parent, or it too willbe considered abstract

InterfaceInterfaces are classes with no implementation.

n Interfaces represent pure design.n Abstract classes represent mixed design and

implementation.An interface consists of only abstract methods andconstants, i.e., static and final.All methods and constants are public.No static methods.An interface cannot be instantiated

Inheritance on Interface

Inheritance relation also applies tointerfacesn superinterface and subinterface

Multiple inheritance allowedn An interface may extend multiple interfacesn A class my implement multiple interfaces

Type ConversionImplicit Conversion

Numeric variables: Any numeric types canbe converted to another numeric type withlarger range, e.g.

char ==> int, int ==> long, int ==> float, float ==> double.

Object reference: An object reference ofclass C can be converted to a reference ofa superclass of C.

Type ConversionExplicit Conversion (Cast)

Numeric variables: Any numeric types canbe explicitly cast to any other numeric type.May lose bits, precision.Object reference: Cast an object referenceof a class to a reference of any other classis:n syntactically allowed; butn runtime checked.

Page 18: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

18

Cast Object Referencesclass Student { ... }class Undergraduate extends Student { ... }class Graduate extends Student { ... }

Student student1, student2;student1 = new Undergraduate(); // okstudent2 = new Graduate(); // ok

Graduate student3;student3 = student2; // compilation error

student3 = (Graduate) student2; // explicit cast, ok

student3 = (Graduate) student1; // compilation ok, run-time error

CASTING class GuiComponent { void setOptimalSize ( ) { . . . } }

class Scrollbar extends GuiComponent { void setOptimalSize ( ) { . . . } int getMinValue ( ) {. . . }

} guiComponent g ; g = new Scrollbar ( ) ;Suppose we know that g currently points to a Scrollbar, and we want

to call: n = g.getMinValue ( ) ;This will cause a compilation error (why?)

CASTING (continued)q The solution is casting (actually down casting).

Ø Casting = convert a variable from one type to another.Ø Down Casting = convert from a superclass to one of its

subclasses.

n = ( (Scrollbar) g).getMinValue ( ) ;Or:Scrollbar sb = (Scrollbar)g ;sb.getMinValue ( ) ;

q We “tell” the compiler that g currently points to a Scrollbar.q if g does not currently point to a Scrollbar, a ClassCastException

is thrown..

Method OverloadingTwo or more methods/constructors with the samename but different numbers or different types ofparameters:…used mainly in the constructors.

void methodA(int i)void methodA(int i, int j)

void methodB(int i)void methodB(float f)

Avoid overloading

Polymorphic Reference

A polymorphic reference is one which canrefer to different types of objects.

POLYMORPHISM : Example GuiComponent g ; if (scrollbarWasSelected) g = new Scrollbar ( ) ; else g = new EditBox ( ) ;

A reference to a superclass can point to objects of its subclasses.

The pointer g is a polymorphic pointer.

Page 19: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

19

Example: Books2.javaclass Books2 { public static void main (String[] args) { Book3[] books = { new Book3("Introduction to Java", 350), new Dictionary3a("Webster English Dictionary",

1500, 52500), new Dictionary3b("Webster English Dictionary",

1500, 52500)}; for (int i = 0; i < books.length; i++) { Book3 book = books[i]; book.info(); System.out.println(); } }}

Example: Books2.javaOutput:

C:\Examples>java Books2Title: Introduction to JavaNumber of pages: 350

Dictionary: Webster English DictionaryNumber of definitions: 52500Definitions per page: 35

Title: Webster English DictionaryNumber of pages: 1500Number of definitions: 52500Definitions per page: 35

DYNAMIC BINDING

class GuiCompontent { void setOptimalSize ( ) { . . . } . . . }

class Scrollbar extends GuiComponent { void setOptimalSize ( ) { . . . } . . . }

class EditBox extends GuiComponent / / use implementation of superclass }

DYNAMIC BINDING

GuiComponent g; / / polymorphic pointer if (scrollbarWasselected) g = new Scrollbar ( ) ; else g = new EditBox ( ) ; g.setOptimalSize ( ) ; / / dynamic binding

SEMI HETEROGENEOUS ARRAY

GuiComponent [ ] ga = new GuiComponent [3] ; ga[0] = new Scrollbar ( ) ; ga[1] = new Scrollbar ( ) ; ga[2] = new EditBox ( ) ; for (int i=0 ; i<ga.length ; i++) { ga[i] . setOptimalSize ( ) ; //line 6}

Q: Which version of setOptimalSize is called in line 6?

Polymorphism allows us to work with an object without knowing its exact type

Abstract Classesabstract member function, means that the function doesnot have an implementation.abstract class, is class that can not be instantiated.

NOTE: Every class with at least one abstract member function mustbe an abstract class

Page 20: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

20

Abstract ClassesAn abstract class is a class with partialimplementation.It implements behaviors that are common to allsubclasses, but defers to the subclasses toimplement others (abstract methods).The subclass of an abstract class must overridethe abstract methods of the parent, or it too willbe considered abstract

Example: Abstract Classes package java.lang; public abstract class Shape {

public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor);

draw(); setCenter(x,y);

setColor(ForeGroundColor); draw(); }}

package java.lang;public class Circle extends Shape {public void draw() {

// draw the circle ... }}

ABSTRACT CLASSq An abstract class is a type of class which we are unable to instantiate.q An abstract class is created for the purpose of subclassung it.

abstract class GuiComponent { . . . } class Scrollbar extends GuiComponent { . . . }

GuiComponent g1, g2; g1 = new Scrollbar ( ) ; / / that’s OK g2 = new GuiComponent ( ) ; / / COMPILATION ERROR !!!

ABSTRACT METHOD

v An abstract method is a method in a superclass, that is declaredbut not implemented.

v class with one or more abstract methods must be an abstractclass.

abstract class GuiComponent { abstract void redraw ( ) ;

}

class Scrollbar extends GuiComponent { void redraw ( ) { . . . }

}

class EditBox extends GuiComponent void redraw ( ) { . . . } }

InterfaceInterfaces are classes with no implementation.

n Interfaces represent pure design.n Abstract classes represent mixed design and

implementation.An interface consists of only abstract methods andconstants (i.e., static and final attributes).All methods and constants are public.No static methods.An interface cannot be instantiated

Interface

Defines a protocol of communicationbetween two objectsContains declarations but noimplementations

Java’s compensation for removing multipleinheritance. You can implement as manyinterfaces as you want.

Page 21: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

21

Interface

interface SouthParkCharacter { void curse();}

interface IChef { void cook(Food);}

interface Singer { void sing(Song);}

class Chef implements IChef, SouthParkCharacter {// overridden methods MUST be public// can you tell why ?public void curse() { … }public void cook(Food f) { … }

}

When to use an interface ?

Perfect tool for encapsulating the innerstructure of classes. Only the interface isexposed.

Final classes

final member dataConstant member

final member functionThe method can’t beoverridden.

final class‘Base’ is final, thus itcan’t be extended

final class Base { final int i=5; final void foo() { i=10; }}

class Derived extends Base {// Error // another foo ... void foo() {

}}

Example: Coin.javapublic class Coin { public final int HEADS = 0; public final int TAILS = 1;

private int face;

public Coin (){ flip(); }

public void flip (){ face = (int) (Math.random() * 2); }

Example: Coin.java public int getFace () { return face; }

public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; }}

Example: CountFlips.java public class CountFlips { public static void main (String[] args) { final int NUM_FLIPS = 1000; int heads = 0, tails = 0; Coin myCoin = new Coin(); for (int count=1; count <= NUM_FLIPS; count++) { myCoin.flip(); if (myCoin.getFace() == myCoin.HEADS) heads++; else tails++; } System.out.println("The number flips: " + NUM_FLIPS); System.out.println("The number of heads: " + heads); System.out.println("The number of tails: " + tails); }}

Page 22: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

22

Example: FlipRace:javapublic class FlipRace { public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; // Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip(); System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2); count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; }

Example: FlipRace:java // Determine the winner if (count1 < GOAL) { System.out.println("Coin 2 Wins!"); } else if (count2 < GOAL) { System.out.println("Coin 1 Wins!"); } else { System.out.println("It's a TIE!"); } }}

Example: Account.java import java.text.NumberFormat; public class Account { private NumberFormat fmt = NumberFormat.getCurrencyInstance(); private final double RATE = 0.045; // interest rate of 4.5% private long acctNumber; private double balance; private String name; public Account(String owner, long account, double initial) { name = owner; acctNumber = account; balance = initial;}

Example: Account.javapublic double deposit (double amount) { if (amount < 0) { // deposit value is negative System.out.println(); System.out.println("Error: ..."); System.out.println(acctNumber + " " + fmt.format(amount)); } else { balance = balance + amount; } return balance;}

Example: Account.javapublic double withdraw(double amount, double fee) { amount += fee; if (amount < 0) { // withdraw value is negative System.out.println ("Error: ..."); } else if (amount > balance) { // withdraw value exceeds balance System.out.println ("Error: ..."); } else { balance = balance - amount; } return balance;}

Example: Account.javapublic double addInterest () { balance += (balance * RATE); return balance;}public double getBalance () { return balance;}public long getAccountNumber () { return acctNumber;}public String toString () { return (acctNumber + "\t" + name + "\t" + fmt.format(balance));}

Page 23: Advanced System Design Using Java Technology A Brief ... - Le · 3 Boolean Type boolean Boolean constants: true false Integer Types int byte Short long Examples of integer constants:

23

Example: BankAccount.javapublic class BankAccounts { public static void main (String[] args) { Account acct1 = new Account("Ted Murphy", 72354, 102.56); Account acct2 = new Account("Jane Smith", 69713, 40.00); Account acct3 = new Account("Edward Demsey", 93757, 759.32); acct1.deposit (25.85); double smithBalance = acct2.deposit (500.00); System.out.println( "Smith balance after deposit: " + smithBalance); System.out.println( "Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50));

Example: BankAccount.java acct3.withdraw (800.00, 0.0); // exceeds balance acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println(); System.out.println(acct1); System.out.println(acct2); System.out.println(acct3); }}

try, catch, throws, exceptionJava has inbuilt mechanisms for when things go wrong

w divide by zero, cant convert a string to a number, sql errors, networkerrors

an Exception object is generated - thrown

your job is to catch exception

statements that could cause a problem are encased in atry statement

Exceptions

Error in SQL processingSQLException

Not enough memory to createexception

OutOfMemoryException

Failure of IOIOException

file does not exist in pathFileNotFoundException

problem converting string to anumber

NumberFormatException

Exception MethodsgetMessage()getErrorCode ()printStackTrace ()

try {// statements that could cause a problem}catch (exctype e) { // error statements}