software engineering methods winter 2002-3 –lecture: prof. shmuel katz. –teaching assistants...

80
Software Engineering Methods Winter 2002-3 – Lecture: Prof. Shmuel Katz. Teaching Assistants Adam Carmi Zvika Gutterman – Grader Berliner Yaniv

Post on 21-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Software Engineering MethodsWinter 2002-3

– Lecture:Prof. Shmuel Katz.

– Teaching Assistants

Adam Carmi

Zvika Gutterman

– GraderBerliner Yaniv

Course Administration

• Follow the web page: www.cs.technion.ac.il/~cs234321

• Email: Use only the course e-mail! [email protected]

• Grade:– test > 50 ? 0.6 HW + 0.4 Test : Test

• Tests– Moed A - 07/Feb/2003– Moed B - 07/Mar/2003

Time Table

• Lecture: Sundays, 10:30-12:30 at Taub 2.

• Group 11:Sundays, 14:30-15:30 at Taub 6.

• Group 12:Tuesdays, 10:30-11:30 at Taub 3.

• Group 13:Wednesdays, 14:30-15:30 at Taub 3.

• Group 14:Cancelled !

Software engineering methods

Written By: Zvi Avidor

Additions: Adam Carmi

Zvi Gutterman

for the c++ programmer

Thanks to Oleg Pozniansky for his comments

Reading

• BooksIn Amazon: – 1662 Entries with Java … (03/2002)– 1918 Entries with Java … (10/2002)

• Course Web Site.

• Java.sun.com

Why Java ?

• Object Oriented

• New (1995)

• Easy to learn

• Many additional features integrated:

Security, JDBC, GUI, MT, Communication,

Documentation, … and lots more!

JVM

• JVM stands for

Java Virtual Machine

• Unlike most other languages, Java “executables” are executed on a CPU that does not exist.

JVM - Cont.C++

file1.cpp

file2.cpp

file1.obj

file2.obj

compilation

main.exe

link

CPU1

CPU2 main.exefile1.obj

file2.obj

execute

Imm

ediate

sources

JVM - Cont.Java

file1.java

file2.java

main.java

sources

compilation

file1.class

file2.class

main.class

Executeon CPU1

Executeon CPU1

java main

java main

Primitive types

• int 4 bytes• short 2 bytes• long 8 bytes• byte 1 byte• float 4 bytes• double 8 bytes• char Unicode encoding (2 bytes) • boolean {true,false}

Behaviors is exactly as in C++

• Constants

37 integer

37.2 float

42F float

0754 integer (octal)

0xfe integer (hexadecimal)

Primitive types - cont.

Wrappers

Java provides Objects which wrap primitive types and supply methods.

Example:

Integer n = new Integer(“4”);int m = n.intValue();

Read more about Integer in JDK Documentation

Hello World

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

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

}

Hello.java

C:\javac Hello.java

C:\java Hello

( compilation creates Hello.class )

(Execution on the local JVM)

More sophisticatedclass Kyle {

private boolean kennyIsAlive_;public Kyle() { kennyIsAlive_ = true; }public Kyle(Kyle aKyle) {

kennyIsAlive_ = aKyle.kennyIsAlive_;}public String theyKilledKenny() {

if (kennyIsAlive_) {kennyIsAlive_ = false;return “You bastards !!!”;

} else {return “?”;

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

Kyle k = new Kyle();String s = k.theyKilledKenny();System.out.println(“Kyle: “ + s);

}}

Default C’tor

Copy C’tor

Results

javac Kyle.java ( to compile )

java Kyle ( to execute )

Kyle: You bastards !!!

Case Sensitive

• Case sensitivity:– String is not the same as string– MAIN is not the same as main

• Java keywords are all lower case– e.g. public class static void

Naming Conventions

• Methods, variables and objects start with a leading lowercase letter :

next, push(), index, etc.

• Classes starts with a leading upper-case letter :

String, StringBuffer, Vector, Calculator, etc.

Naming Conventions (2)

• Constants (final) are all upper-case : DEBUG, MAX_SCROLL_X, CAPACITY.

E.g.

final double PI = 3.1415926;

• Word separation in identifiers is done by capitalization, except for constants where underscore is used.

Comments

• C++ Like:// bla bla ../* this is a bla bla */

• And JavaDoc Comments:/** comment */

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}

Everything is a referenceto an Object

Every variable in Java (almost…) is a reference/pointer.

C++

5

9

a

b

MyObject *x ( not initialized !!!)

Java

MyObject x

a=b

MyObject x(5)

Since we’re handling pointers, the following is obvious :

5

9

a

b

N/A

Garbage Collection• In C++ we use the ‘delete’ operator to release

allocated memory. ( Not using it means : memory leaks )

• In Java there is no ‘delete’ and there are no memory leaks ! How could this be ?– answer : reference count

6a

1

6a

2b{

b=a}

Garbage collection - cont.

6a

2b

{ Number b=a;}

6

1

Out ofscope

6

0

Garbage Collector

Arrays

• Array is an object

• Array size is fixed

Animal[] arr; // nothing yet …

arr = new Animal[4]; // only array of pointers

for(int i=0 ; i < arr.length ; i++) {arr[i] = new Animal();

// now we have a complete array

Arrays - Multidimensional

• In C++ Animal arr[2][2]

Is:

• In Java

What is the type of the object here ?

Animal[][] arr= new Animal[2][2]

String is an Object

• Constant strings as in C, does not exist.

• The function call foo(“Hello”) creates a String object, containing “Hello”, and passes reference to it to foo.

• There is no point in writing :

• The String object is a constant. It can’t be changed using a reference to it.

String s = new String(“Hello”);

Static• Member data - Same data is used for all the

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

Output:

1510

Static – cont.• Member function

– Static member function can access only static members

– Static member function can be called without an instance.

Class TeaPot {private static int numOfTP = 0;private Color myColor_;public TeaPot(Color c) {

myColor_ = c; numOfTP++;

}public static int howManyTeaPots()

{ return numOfTP; }

// error :public static Color getColor()

{ return myColor_; }}

Example

Static - cont.

Usage:

TeaPot tp1 = new TeaPot(Color.RED);

TeaPot tp2 = new TeaPot(Color.GREEN);

System.out.println(“We have “ + TeaPot.howManyTeaPots()+ “Tea Pots”);

Packages

• Java code has hierarchical structure.• The environment variable CLASSPATH contains

the directory names of the roots.• Every Object belongs to a package ( ‘package’

keyword)• Object’s full name contains the full name of the

package containing it.

Packages – After compilation

package P1;public class C1 {}

package P2;public class C2 {}

package P1;class C3 {}

package P3.A.B;class C1 {}

F:\MyClasses\P1\C1.class F:\MyClasses\P2\C2.class

F:\MyOtherClasses\P1\C3.class F:\MyClasses\P3\A\B\C1.class

When compiling the -d option defines the target root

Directories are automatically

created

Packages - Example, cont.

F:\MyClasses\P1\C1.class

F:\MyClasses\P2\C2.class

F:\MyOtherClasses\P1\C1.class

F:\MyClasses\P3\A\B\C1.class

Assume that CLASSPATH=F:\MyClasses;F:\MyOtherClasses

C1 c=new C1(); Error !!

P1.C1 c=new P1.C1();

import P1.*;C1 c=new C1();

import P3.A.B.C1;import P1.*;C1 c=new C1();

Access control public class

– ‘new’ is allowed from other packages ( default: only from the same package (note: not necessarily

from the same file) )

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

• public member (function/data) – Can be called/modified from outside.

• Protected– Can called/modified from derived classes

• private– Can called/modified only from the current class

• Default ( if no access modifier stated )– Usually referred to as “Friendly”.

– Can called/modified/instantiated from the same package.

Access Control - cont.

Base

Derived

Package P1

Package P2

SomeClass

prot

ecte

d public

SomeClass2

private

Friendl

yInheritance

Usage

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

Polymorphism

• Inheritance creates an “is a” relation:

For example, if B inherits from A, than we say that “B is also an A”.

Implications are:– access rights (Java forbids reducing of access rights)

- derived class can receive all the messages that the base class can.

– behavior

– precondition and postcondition

Inheritance (2)• In Java, all methods are virtual :

class Base { void foo() { System.out.println(“Base”); }}class Derived extends Base { void foo() { System.out.println(“Derived”); }}public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Derived.foo() will be activated }}

Abstract• abstract member function, means that the function

does not have an implementation.• abstract class, is class that can not be instantiated.

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

Example

Abstract - Examplepackage 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 ... }}

Interface• abstract “class”

• Helps defining a “usage contract” between classes

• All methods are public

• Java’s compensation for removing the multiple inheritance. You can “inherit” as many interfaces as you want.

Example * - The correct term is “to implement”an interface

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 classes inner structure. Only the interface will be exposed

final

• final member dataConstant member

• final member function The method can’t be overridden.

• final class‘Base’ is final, thus it can’t be extended

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

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

Collectionsbehavior

implementation

HashSet TreeSet

Set

LinkedList ArrayList

ArrayMap HashMap TreeMap

MapList

Collection Iteratorproduces

import java.util.*;

class ListTest { static void showCollection(Collection col) { Iterator it = col.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } static void showList(List lst) {

for(int i=0;i<lst.size();i++) { System.out.println("" + i + ": " + lst.get(i)); } }

public static void main(String[] args) { LinkedList ll = new LinkedList(); ArrayList al = new ArrayList(); ll.add("one");ll.add("two");ll.add("three"); al.add("one");al.add("two");al.add("three"); showList(ll);showCollection(ll); showList(al);showCollection(al); }}

List

0: one1: two2: threeonetwothree0: one1: two2: threeonetwothree

import java.util.*;

class MapTest { static void ShowMap(Map m) { Set s = m.entrySet(); Iterator it = s.iterator(); while(it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); // downcast System.out.println(entry.getKey() +

"-->" + entry.getValue()); } } public static void main(String[] args) { TreeMap tm = new TreeMap(); HashMap hm = new HashMap();

tm.put(new Integer(1),"one");tm.put(new Integer(2),"two"); tm.put(new Integer(3),"three"); hm.put(new Integer(1),"one");hm.put(new Integer(2),"two"); hm.put(new Integer(3),"three"); ShowMap(tm); ShowMap(hm); }}

Map

1-->one2-->two3-->three3-->three2-->two1-->one

IO - Introduction• Definition

– Stream is a flow of data• characters read from a file

• bytes written to the network

• …

• Philosophy – All streams in the world are basically the same.

– Streams can be divided (as the name “IO” suggests) to Input and Output streams.

• Implentation– Incoming flow of data implements “Reader”

– Outgoing flow of data implements “Writer”

SourceSink Filter

Stream concepts

IO - Examples (1)

Reading input by lines

FileReader in = new FileReader(“CrimeAndPunishment.txt”));

String s;

while((s = in.readLine()) != null) {System.out.println(s);

}

IO - Examples (2)

Reading standard input

BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)));

System.out.println(“Enter a line:”);System.out.println(stdin.readLine());

System.in is a reference of type InputStream.InputStream, is the “Reader” of JDK 1.0 . It is still required sometimes ( as in this case, where System.in type must be keptfor backward compatibility )

IO - Examples (3)

Reading from String

StringReader in = new StringReader(“Hello World”);

int c;

while((c = in.read()) != -1)System.out.println((char)c);

Advanced Usage

// Load drug information from a reader stream.

public void load(Reader r) throws IOException {

// File is ordered in 3 columns: name toxicity effectDuration

StreamTokenizer st = new StreamTokenizer(r);

// Check if there is a data to read

...

public static void main(String[] arg) {

DrugInfo drug;

try {

drug = new DrugInfo();

drug.load(new StringReader("LSD 4 4"));

...

} ...

from DrugInfo class

IO - Advanced topics

• Redirecting standard IO– System contains setIn, setOut and setErr.

• E.g. System.setIn(new FileInputStream(“x.dat”));

– Standard streams could be from/to anything you want!

• Compression– Read about ZipInputStream and ZipOutputStream

Exception - Why ?

• Handling all possible irregularities in the execution can be too complicated– Too many “if” statements– Return value must always be an error value– Need to handle errors in constructor (there is no

return value from a constructor)

Exceptions – How to handle ?public class ThrowingBufferedReader extends BufferedReader {

public ThrowingBufferedReader(Reader r) {

super(r);

}

public ThrowingBufferedReader(Reader r, int sz) {

super(r,sz);

}

public String readLine() throws EOFException,IOException{

String s;

s = super.readLine();

if (s == null) throw new EOFException();

return s;

}

}

Exception – How to handle (2)

void foo(Reader r) { ThrowingBufferedReader br = new ThrowingBufferedReader(r); try { // Suppose we’re expecting three lines to appear // in the stream. a = br.readLine(); b = br.readLine(); c = br.readLine(); } catch(EOFException e) { System.err.println(“Error with input”); } catch(Exception e) { System.err.println(“Caught unexpected exception”); } }

Exception - What is it ?• Exception is an Object

• Exception class must be descendent of Throwable.

• When thrown– Stops the current path of execution.

– Control is returned to the first matching catch block on the stack.

• Every method must declare the exceptions it might throw.

Exceptions – Creating your own

Class UglyException extends Exception { public String response_; UglyException(String str) {

response_ = str; }}

class Woman { void התחל() throws UglyException { // … throw new UglyException(“Go away !”); // … }}

Inner class

class A { int i; public class B { int getI() { return i; } }

public static class C { int getI() { // error return i; } }

}

Class B holds a hidden referenceto the father class A

With the static keyword, C’s name is changed toA.C

Note: This is the last static usage.

Anonymous class

Rational

- Suppose you have a class, which has only one instantiation place

- Suppose that this class is very small

- Suppose you have several classes with the characteristics above

Do you really want to define a formal class for each and every such class ? - Sure you don’t ….

Anonymous class - cont.

Define a derived class

class Derived extends Base { void foo() { print(“Derived”); }}

Instantiation

bar(new Derived());

class Base { void foo() { System.out.println(“Base”); }}

Define & instantiate

bar( new Base() { void foo() { print(“Derived”); } } );

More meaningful examples when we will talk about GUI

Another call with the exact same class is IMPOSSIBLE !

GUI ( Graphical User Interface)

• AWT - Abstract Windows Toolkit – Usually referred to as Awful Windows Toolkit (in Java 1.0)

– Defines Event-Based Framework for writing GUI.

• Swing– Rich set of easy-to-use, easy-to-understand GUI

Components (called Java Beans) to allow you creating a GUI that you can be satisfied with.

It don’t mean a thing, if it ain’t got that Swing …

GUI - cont.

• GUI in Java has hierarchical structure

JComponent

Component

JButtom

Container

1

*

Window

Dialog

JDialog

1

*

JLabelJCheckBox

Event Model• A component can initiate (“fire”) an event.

• Each type of event is represented by a distinct class (derived from ComponentEvent )

• When an even is fired, it is received by one or more “listeners”, which act on that event. ( listener is a class, derived from EventListener )

• Each event listener is an object of a class that implements a particular type of listener interface.

Example - MessageBox

package Mackey;

import java.awt.*; import javax.swing.*; import javax.swing.border.*;import java.awt.event.*;

public class MackeyBox extends JDialog { /** Panel serves as a container. **/ JPanel pnlMessageBox = new JPanel();

/** Components in the action **/ JButton btnCancel = new JButton(“Cancel”); JButton btnMkay = new JButton(“Mkay”); JTextArea txtQuestion = new JTextArea(“

Do you want to continue ?”);

/** c’tor **/ public MackeyBox(Frame frame,

String title, boolean modal) { // call JDialog ctor. // if frame is closed, out dialog will be disposed. super(frame, title, modal);

try { jbInit();// initialize all the components pack(); // shrink the window to match // the preffered size of the // contained components } catch(Exception ex) { ex.printStackTrace(); }}

public MackeyBox() { // transfer control from // one ctor to another this((Frame)null, "", false); }

/** entry point **/ public static void main(String[] args) { MackeyBox mb = new MackeyBox(); mb.setVisible(true); }

/** initialize components **/void jbInit() throws Exception {

txtQuestion.setWrapStyleWord(true); txtQuestion.setEditable(false); txtQuestion.setFont(

new Font("Dialog", 0, 25)); txtQuestion.setBounds(

new Rectangle(36, 22, 225, 90)); txtQuestion.setLineWrap(true); txtQuestion.setBackground(SystemColor.text); pnlMessageBox.setLayout(null); pnlMessageBox.setPreferredSize(

new Dimension(291, 172));

btnCancel.setBounds( new Rectangle(157, 132, 80, 27));

// notice the anonymous class usage here !!! btnCancel.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { /* The reason we can call this method, is because the created anonymous class, has a hidden pointer to the current instance of MackeyBox class. */

btnCancel_mousePressed(e); } });

btnMkay.setBounds(new Rectangle(36, 132, 79, 27));

btnMkay.addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) {

System.out.println("Mkay pressed"); System.exit(0);

} });

pnlMessageBox.add(btnMkay); pnlMessageBox.add(btnCancel); pnlMessageBox.add(txtQuestion); getContentPane().add(pnlMessageBox); setResizable(false);}

void btnCancel_mousePressed(MouseEvent e) {System.out.println("Cancel pressed");

System.exit(0); }}

(Much) Shorter version

Code

/** entry point **/public static void main(String[] args) { Object[] options = { "Mkay", "Cancel" }; int selectedValue =

JOptionPane.showOptionDialog(null, "Do you want to continue ?", "",

JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,null, options, options[0]);

System.out.println(selectedValue);}

Layout Manager

• null – Each component has specific place and size.

• FlowLayout – Components are added from left to right,

top to bottom, by the order they are added to the container

(components are sized according to preferred size)

• GridLayout – Table-like order.

• BorderLayout – 5 regions subdivision.

• GridbagLayout – The most robust and complicated one.

• BoxLayout – Order by y or x axis

Example

BoxLayout (y-axis) GridLayout (2,2)

BoxLayout (x-axis)

class MyDialog extends JDialog{

...

Container cnt = this.getContentPane();

cnt.setLayout(new BoxLayout(cnt,BoxLayout.Y_AXIS));

JPanel pnlMain = new JPanel();

pnlMain.setLayout(new GridLayout(2,2,10,10));

JPanel pnlButtons = new JPanel();

pnlButtons.setLayout(

new BoxLayout(pnlButtons,BoxLayout.X_AXIS));

pnlMain.add(lblLogin);

pnlMain.add(txtLogin);

pnlMain.add(lblPass);

pnlMain.add(txtPass);

pnlButtons.add(btnCont);

pnlButtons.add(btnExit);

pnlButtons.add(btnExpload);

txtLogin.setPreferredSize(new Dimension(200,30));

cnt.add(pnlMain);

cnt.add(pnlButtons);

this.setResizable(false); …}

Setting theGrid section

Setting theButtons section

MainCode

full code on the web-site

Java Applet• Applet is basically, a panel, with special functions,

required for working with a browser.– init() Called when the applet is first created to perform

the first-time initialization

– start() Called every time the applet moves into sight on the Web-Browser

– paint() Allows special painting of the applet.

– stop() Called every time the applet moves out of sight on the Web-Browser.

– destroy() Called every time the applet is being unloaded from the page

More material is out of the scope of this course ...