sep 2005 sdp-msc slide 1 section 7 object oriented programming

167
Sep 2005 1 Section 7 Object Oriented Programming

Upload: lynne-elliott

Post on 03-Jan-2016

217 views

Category:

Documents


1 download

TRANSCRIPT

Sep 2005 SDP-MSc Slide

1

Section 7

Object Oriented Programming

Sep 2005 SDP-MSc Slide

2

Object Oriented Programming

Section 7.1

Class Definition

using System;

class Counter{ private int number; private string name; public Counter(int v, String n){ this.number = v;

this.name = n;}

public void increment(){this.number++;}

public int read_value(){ return this.number;}

}

public class Ex1{

public static void Main(){

Counter c1; c1=new Counter(6, "Days");

c1.increment(); c1.increment(); int res=c1.read_value(); Console.WriteLine("Value: {0}",res); }

}

public class Ex1{public static void Main(){ Counter c1=new Counter(6,"Days Worked");

int choice=0; while (choice !=3){

Console.WriteLine(":");Console.WriteLine("1: Increment");Console.WriteLine("2: Read Value");Console.WriteLine("3: Exit");Console.Write("Enter Choice: ");string temp=Console.ReadLine();

choice=Convert.ToInt32(temp);switch(choice){ case 1: c1.increment(); break; case 2: int res=c1.read_value(); Console.WriteLine(": {0}",res); break; }}}}

Alternative Test Fn

Sep 2005 SDP-MSc Slide

6

Allows Read/Write access to member data:

class Counter{ private string name; private int number; public int NUMBER{ get { return number;} set { number=value;} // ‘value’ a keyword } public Counter(int v, String n){ this.number = v;

this.name = n;}

public void increment(){this.number++;}

public int read_value(){ return this.number;}

}

Properties

public class Ex1{

public static void Main(){

Counter c1; c1=new Counter(6, "Days");

c1.NUMBER=9; c1.increment(); c1.increment(); int res=c1.NUMBER; Console.WriteLine("Value: {0}",res); }

}

Properties

class Account{ private int accNo; private int balance; public Account(int No, int bal){ this.balance=bal;

this.accNo=No;}public int getAccNo(){return accNo;}

public int getBalance() {return balance;}

public void credit(int amount){ balance+=amount;}

public void print_details(){ System.out.print("\nAccount Details”+ “\nNo:”); System.out.println(accNo+" Balance:"+balance);}}

Sep 2005 SDP-MSc Slide

10

public class Ex2{

public static void Main(){

Account a1 = new Account(1,100); Account a2 = new Account(2,200); a1.credit(50); a1.print_details(); a2.print_details(); }}

Sep 2005 SDP-MSc Slide

11

Account DetailsNo:1 Balance:150

Account DetailsNo:2 Balance:200

Sep 2005 SDP-MSc Slide

12

public class Ex1{public static void Main(){ Account a1 = new Account(1,100);

int amt=0, choice=0; while (choice !=3){

Console.WriteLine(":");Console.WriteLine("1: Deposit");Console.WriteLine("2: Check Balance");Console.WriteLine("3: Exit");Console.Write("Enter Choice:");

choice=Convert.ToInt32(Console.ReadLine());switch(choice){

case 1: Console.WriteLine("Enter Amount"); amt=Convert.ToInt32(Console.ReadLine());

a1.credit(amt); break;case 2: a1.print_details(); break;

} }}}

Alternative Test Fn

Sep 2005 SDP-MSc Slide

13

Alternative Version using properties

get, set

Sep 2005 SDP-MSc Slide

14

class Account{ private int accNo; private int balance; public Account(int No, int bal){ this.balance=bal;

this.accNo=No;}public int Account_No{

get {return accNo;} set {accNo= value;}}

public int getBalance { get{return balance;}} // only read access

public void credit(int amount){ balance+=amount;}

public void print_details(){ Console.Write("Details"+ ":"); Console.WriteLine("{0} Balance: {1}",accNo,balance);}}:

Sep 2005 SDP-MSc Slide

15

public class Ex1{

public static void Main(){

Account a1 = new Account(1,100); Account a2 = new Account(2,200);

a1.Account_No=678; // set int res=a1.getBalance; // get

Console.WriteLine("a1 bal={0}",res); a1.print_details(); a2.print_details(); }

}

Sep 2005 SDP-MSc Slide

16

Indexers

Array type indexing of a class object

Sep 2005 SDP-MSc Slide

17

class Vector{ private int count=4;private int []arr={3,3,6,7};

public int this[int index]{get{ if (index < count) return arr[index]; else return 0;}

set { arr[index]=value;}}} }

:

Sep 2005 SDP-MSc Slide

18

public class Ex1{

public static void Main(){

Vector v =new Vector(); v[1]=9; // setConsole.WriteLine("value={0}",v[1]); // get

}}

Sep 2005 SDP-MSc Slide

19

class LList{private int[] list;private int count;private int size;

public LList(int s){ this.size=s; this.count=0;

this.list=new int[s];}

public void insert(int v){ if (count<size){

list[count]=v; count++;}}:

Sep 2005 SDP-MSc Slide

20

:

public void print_LList(){ Console.WriteLine("");

for(int i=0;i<count;i++){ Console.WriteLine(" {0}",list[i]);

}}

}

Sep 2005 SDP-MSc Slide

21

public class Ex1{

public static void Main(){ LList s = new LList(5);

int val=0, choice=0;while (choice !=3){

Console.WriteLine(":");Console.WriteLine("1: Insert");Console.WriteLine("2: Print Stack");Console.WriteLine("3: Exit"); :

Sep 2005 SDP-MSc Slide

22

:Console.Write("Enter Choice:");

choice=Convert.ToInt32(Console.ReadLine());

switch(choice){ case 1: Console.Write("Enter Value");

val=Convert.ToInt32(Console.ReadLine()); s.insert(val); break;

case 2: s.print_LList(); break; } } }}

Sep 2005 SDP-MSc Slide

23

• Version 2 of Account Class

- static variables

Sep 2005 SDP-MSc Slide

24

class Account{ private int accNo; private int balance; private static int count=0; public Account(int bal){ this.balance=bal;

this.accNo=++count;}

public int getAccNo(){return accNo;}

public int getBalance() {return balance;}

public static int read_count(){return count;}

public void credit(int amount){ balance+=amount;}:

}

Sep 2005 SDP-MSc Slide

25

public class Ex1{

public static void Main(){ Account a1 = new Account(100);

Account a2 = new Account(200); a1.credit(50); a1.print_details(); a2.print_details(); int total=Account.read_count(); Console.WriteLine("no of Accounts:{0}",total);

}}

Sep 2005 SDP-MSc Slide

26

Account DetailsNo:1 Balance:150

Account DetailsNo:2 Balance:200

Total no of Accounts:2

Sep 2005 SDP-MSc Slide

27

Q71. Complete the following class & main menu

class Time{ private int sec; private int min; public Time(int m, int s){ ….. public void increment_sec(){ …. public void print_time(){ …..

}

public class Q71{public static void Main(){…

Note: Sec ==60?

Sep 2005 SDP-MSc Slide

28

Q72. Complete the following class & main menu

class Item{private int lotno;private String bidder;private int bid;

public Item(int l,String bn, int b){...public void nextbid(String b_name, int amt){...public void print_details(){ }}

public class Q72{public static void Main(){…

Note: next bid only accepted if > current bid

Online Auction

Sep 2005 SDP-MSc Slide

29

Now Version 3:

Inheritance

class Counter{ protected int value; private string name;

public Counter(int v, String n){ this.value = v; this.name = n;}

public void increment(){this.value++;}

public int read_value(){ return this.value;}

}

class MyCounter : Counter{ private char sign;

public MyCounter(int v, String n, char s):base(v,n){ this.sign = s;}

public void decrement() {this.value--;}

new public int read_value(){ if (this.sign=='-') return this.value * -1;

else return this.value;}

public void change_sign(){ if (this.sign=='-') this.sign = '+';

else this.sign = '-';}}

public class Ex1{public static void Main(){ MyCounter c1=new MyCounter(6,"Days Worked",'+'); int choice=0; while (choice !=4){

Console.WriteLine(":");Console.WriteLine("1: Increment");Console.WriteLine("2: Decrement");Console.WriteLine("3: Read Value");Console.WriteLine("4: Exit");Console.Write("Enter Choice: ");string temp=Console.ReadLine();choice=Convert.ToInt32(temp);switch(choice){

case 1: c1.increment(); break;case 2: c1.decrement(); break;case 3: int res=c1.read_value(); Console.WriteLine(": {0}",res); break;}}}}

class Account{ private int accNo; protected int balance; public Account(int No, int bal){ this.balance=bal;

this.accNo=No;}public int getAccNo(){return accNo;}

public int getBalance() {return balance;}

public void credit(int amount){ balance+=amount;}

public void print_details(){ Console.Write("Details"+ ":"); Console.WriteLine("{0} Balance: {1}",accNo,balance);}}

Sep 2005 SDP-MSc Slide

34

class ATMaccount: Account{ private int pin;public ATMaccount(int n,int bal, int pin):base(n,bal)

{this.pin=pin;}

public bool debit(int amount){ if (amount > balance) return false;

else { balance = balance - amount; return true;}}

public bool pinOK(int pin){ if (this.pin==pin) return true;

else return false;}

new public void print_details(){ base.print_details(); Console.WriteLine("Pin: {0}",pin);}

}

Sep 2005 SDP-MSc Slide

35

public class Ex1{

public static void Main(){ ATMaccount a1 = new ATMaccount(3214, 100, 2222); Console.Write("Enter Pin"); int pin=Convert.ToInt32(Console.ReadLine()); while (a1.pinOK(pin)==false) { Console.Write("Enter Pin"); pin=Convert.ToInt32(Console.ReadLine());}

int amt=0, choice=0; :

Sep 2005 SDP-MSc Slide

36

:while (choice !=4){

Console.WriteLine(":");Console.WriteLine("1: Deposit");Console.WriteLine("2: Withdraw");Console.WriteLine("3: Check Balance");Console.WriteLine("4: Exit");Console.Write("Enter Choice:");

choice=Convert.ToInt32(Console.ReadLine());switch(choice){ case 1: Console.Write("Enter Amount: ");

amt=Convert.ToInt32(Console.ReadLine()); a1.credit(amt); break;

case 2: Console.Write("Enter Amount: "); amt=Convert.ToInt32(Console.ReadLine());

a1.debit(amt); break; case 3: a1.print_details(); break;

}}}}

Sep 2005 SDP-MSc Slide

37

Sep 2005 SDP-MSc Slide

38

Section 1

Object Oriented Programming

(Revision)

Sep 2005 SDP-MSc Slide

39

class LList{private int[] list;private int count;private int size;

public LList(int s){ this.size=s; this.count=0;

this.list=new int[s];}

public void insert(int v){ if (count<size){

list[count]=v; count++;}}:

Sep 2005 SDP-MSc Slide

40

:

public void print_LList(){ Console.WriteLine("");

for(int i=0;i<count;i++){ Console.WriteLine(" {0}",list[i]);

}}

}

Sep 2005 SDP-MSc Slide

41

public class Ex1{

public static void Main(){ LList s = new LList(5);

int val=0, choice=0;while (choice !=3){

Console.WriteLine(":");Console.WriteLine("1: Insert");Console.WriteLine("2: Print Stack");Console.WriteLine("3: Exit"); :

Sep 2005 SDP-MSc Slide

42

:Console.Write("Enter Choice:");

choice=Convert.ToInt32(Console.ReadLine());

switch(choice){ case 1: Console.Write("Enter Value");

val=Convert.ToInt32(Console.ReadLine()); s.insert(val); break;

case 2: s.print_LList(); break; } } }}

Sep 2005 SDP-MSc Slide

43

class LList{protected int[] list;protected int count;private int size;

public LList(int s){ this.size=s; this.count=0;

this.list=new int[s];} public void insert(int v){ if (count<size){

list[count]=v; count++;}}

public void print_LList(){:

Sep 2005 SDP-MSc Slide

44

class Stack : LList{

public Stack(int s):base(s){}

public int remove(int v){ int res=-1;

if (count >0){ res=list[count-1]; count--;}

return res; }

}

Sep 2005 SDP-MSc Slide

45

public class Ex1{

public static void Main(){ Stack s = new Stack(5); int val=0, choice=0; while (choice !=4){ Console.WriteLine(":"); Console.WriteLine("1: Insert"); Console.WriteLine("2: Remove"); Console.WriteLine("3: Print Stack"); Console.WriteLine("4: Exit");

Console.Write("Enter Choice:"); choice=Convert.ToInt32(Console.ReadLine()); :

Sep 2005 SDP-MSc Slide

46

: switch(choice){

case 1: Console.Write("Enter Value"); val=Convert.ToInt32(Console.ReadLine());

s.insert(val); break; case 2: val=s.remove(val); if (val>=0)

Console.Write("{0} Deleted",val); break;

case 3: s.print_LList(); break; } } }}

Sep 2005 SDP-MSc Slide

47

Q73. Complete the following class & main menu

class MyTime : Time

1- additional parameter ‘hour’

2. Modified functions - increment_sec() - print_time()

3. New function - increment_hour()

Note: ‘protected’ data

Sep 2005 SDP-MSc Slide

48

Q74. Complete the following class & main menu

class Exp_Item : Item{ // bid only accepted if > limit also

1- additional parameter ‘limit’

2. Modified functions - nextbid(String b_name, int amt)

- print_details()

3. New function - set_limit(int l)

Note: ‘protected’ data

Sep 2005 SDP-MSc Slide

49

Next Version4: Polymorphism

(Dynamic Binding)

Sep 2005 SDP-MSc Slide

50

class Base{ public void f1() {Console.WriteLine("f1 base");} public virtual void f2() {Console.WriteLine("f2 base");}}class Derv: Base{

new public void f1() {Console.WriteLine("f1 derv");} public override void f2() {Console.WriteLine("f2 derv");}}

Sep 2005 SDP-MSc Slide

51

public class Ex1{

public static void Main(){Base b=new Base();b.f1();b.f2();Console.Read();

}}

Sep 2005 SDP-MSc Slide

52

Sep 2005 SDP-MSc Slide

53

public class Ex1{

public static void Main(){Base b=new Derv();b.f1();b.f2();Console.Read();

}}

Sep 2005 SDP-MSc Slide

54

Sep 2005 SDP-MSc Slide

55

class Account{ private int accNo; protected int balance; public Account(int No, int bal){ this.balance=bal;

this.accNo=No;}public int getAccNo(){return accNo;}public int getBalance() {return balance;}public void credit(int amount){ balance+=amount;}public virtual bool pinOK(int pin){return true;}

public virtual bool debit(int amount){ return true;}

public virtual void print_details(){ Console.Write("Details"+ ":"); Console.WriteLine("{0} Balance: {1}",accNo,balance);}} :

}

Sep 2005 SDP-MSc Slide

56

class ATMaccount: Account{ private int pin;public ATMaccount(int n,int bal, int pin):base(n,bal)

{this.pin=pin;} public override bool debit(int amount){

Console.WriteLine("derv"); if (amount > balance) return false; else { balance = balance - amount;

return true;}} public override bool pinOK(int pin){

if (this.pin==pin) return true; else return false;}public override void print_details(){ base.print_details(); Console.WriteLine("Pin: {0}",pin);}

}

Sep 2005 SDP-MSc Slide

57

public class Ex1{public static void Main(){ Account a1 = new ATMaccount(3214, 100, 2222); Console.Write("Enter Pin"); int pin=Convert.ToInt32(Console.ReadLine()); while (a1.pinOK(pin)==false) { Console.Write("Enter Pin"); pin=Convert.ToInt32(Console.ReadLine());} int amt=0, choice=0; while (choice !=4){ :

Sep 2005 SDP-MSc Slide

58

:switch(choice){

case 1: Console.Write("Enter Amount: "); amt=Convert.ToInt32(Console.ReadLine());

a1.credit(amt); break;

case 2: Console.Write("Enter Amount: "); amt=Convert.ToInt32(Console.ReadLine());

a1.debit(amt); break;

case 3: a1.print_details(); break;}}}}

Sep 2005 SDP-MSc Slide

59

public class Ex2{

public static void Main(){ Account[] array = new Account[2];

array[0] = new ATMaccount(3210,100,2222); array[1] = new Account(3211,200); if (array[0].pinOK(2222)==true){

array[0].credit(50); } for(int i=0; i<2;i++)

{array[i].print_details();} }

}

Sep 2005 SDP-MSc Slide

60

Account DetailsNo:1 Balance:150Pin: 2222

Account DetailsNo:2 Balance:2000

Sep 2005 SDP-MSc Slide

61

Version 5:

Abstract Classes

Sep 2005 SDP-MSc Slide

62

abstract class Account{ private int accNo; protected int balance;

public Account(int No, int bal){ this.balance=bal; this.accNo=No;}

public int getAccNo(){return accNo;}

public int getBalance() {return balance;}

public void credit(int amount){ balance+=amount;} public abstract bool pinOK(int pin);

public abstract bool debit(int amount); :}

abstract classes & interfaces

Sep 2005 SDP-MSc Slide

63

class ATMaccount: Account{ private int pin;public ATMaccount(int n,int bal, int pin):base(n,bal)

{this.pin=pin;} public override bool debit(int amount){

Console.WriteLine("derv"); if (amount > balance) return false; else { balance = balance - amount;

return true;}} public override bool pinOK(int pin){

if (this.pin==pin) return true; else return false;}public override void print_details(){ base.print_details(); Console.WriteLine("Pin: {0}",pin);}

}

Sep 2005 SDP-MSc Slide

64

public class Ex2{

public static void Main(){ Account[] array = new Account[2];

array[0] = new ATMaccount(3210,100,2222); array[1] = new ATMaccount(3211,200,3333); if (array[0].pinOK(2222)==true){

array[0].credit(50); } for(int i=0; i<2;i++)

{array[i].print_details();} }

}

Sep 2005 SDP-MSc Slide

65

Account DetailsNo:1 Balance:150Pin: 2222

Account DetailsNo:2 Balance:200Pin: 3333

pure abstract class

abstract class Counter{

public abstract void increment();

public abstract void decrement();

public abstract int read_value();}

class MyCounter : Counter{ private int value; private String name; private char sign; public MyCounter(int v, String n, char s) { this.value = v;

this.name = n;this.sign = s;}

public override void decrement() {this.value--;} public override void increment(){this.value++;} public override int read_value(){ if (this.sign=='-') return this.value * -1;

else return this.value;} public void change_sign(){ if (this.sign=='-') this.sign = '+';

else this.sign = '-';}}

public class Ex1{public static void Main(){ MyCounter c1=new MyCounter(6,"Days Worked",'+'); int choice=0; while (choice !=4){

Console.WriteLine(":");Console.WriteLine("1: Increment");Console.WriteLine("2: Decrement");Console.WriteLine("3: Read Value");Console.WriteLine("4: Exit");Console.Write("Enter Choice: ");string temp=Console.ReadLine();

choice=Convert.ToInt32(temp);switch(choice){ case 1: c1.increment(); break; case 2: c1.decrement(); break; case 3: int res=c1.read_value(); Console.WriteLine(": {0}",res); break;}}

}}

interfaces

interface Counter{

void increment();

void decrement();

int read_value();}

Sep 2005 SDP-MSc Slide

72

class MyCounter : Counter{ private int value; private String name; private char sign; public MyCounter(int v, String n, char s) { this.value = v;

this.name = n;this.sign = s;}

public void decrement() {this.value--;} public void increment(){this.value++;} public int read_value(){ if (this.sign=='-') return this.value * -1;

else return this.value;} public void change_sign(){ if (this.sign=='-') this.sign = '+';

else this.sign = '-';}}

Sep 2005 SDP-MSc Slide

73

public class Ex1{public static void Main(){ MyCounter c1=new MyCounter(6,"Days Worked",'+'); int choice=0; while (choice !=4){

Console.WriteLine(":");Console.WriteLine("1: Increment");Console.WriteLine("2: Decrement");Console.WriteLine("3: Read Value");Console.WriteLine("4: Exit");Console.Write("Enter Choice: ");string temp=Console.ReadLine();

choice=Convert.ToInt32(temp);switch(choice){ case 1: c1.increment(); break; case 2: c1.decrement(); break; case 3: int res=c1.read_value(); Console.WriteLine(": {0}",res); break;}}

}}

Sep 2005 SDP-MSc Slide

74

interface X{void f0();

}class Base{

public void f1(){Console.WriteLine("f1 base");}

public virtual void f2(){Console.WriteLine("f2 base");}}

class Derv: Base,X{ new public void f1(){Console.WriteLine("f1 derv");}

public override void f2(){Console.WriteLine("f2 derv");} public void f0(){Console.WriteLine("f interface");}}}}

Sep 2005 SDP-MSc Slide

75

<< abstract>>Counter

protected int value

Counter (int v){abstract} void increment(){abstract} void decrement()double read_val();

Step_by_one

void increment() // step value up by 1void decrement() // step down by 1

Step_by_two

void increment() // step value up by 2void decrement() // step down by 2

Q75. Using the following class diagram as a basis outline a complete application which demonstrates how an ‘abstract’ class is defined and used in java.

Use the following Test Fn

Sep 2005 SDP-MSc Slide

76

public class Q75{ public static void main(String[] args){ Counter[] c1=new Counter[2];

Steps_of_one s1=new Steps_of_one(5); Steps_of_two s2=new Steps_of_two(5); c1[0]=s1; c1[1]=s2;

int choice=0, index=0;while (choice!=4){Console.WriteLine(":");Console.WriteLine("1: Increment");Console.WriteLine("2: Decrement");Console.WriteLine("3: Read Value");Console.WriteLine("4: Exit");Console.Write("Enter Choice: ");string temp=Console.ReadLine();

choice=Convert.ToInt32(temp); Console.Write(" Enter Counter Index (0 or 1:");

string temp1=Console.ReadLine(); choice=Convert.ToInt32(temp1);

switch(choice){case 1: c1[index].increment(); break;case 2: c1[index].decrement(); break;case 3: System.out.println("Value= "+ c1[index].readvalue()); break;}

} }}

Sep 2005 SDP-MSc Slide

77

Q76. Using the following class diagram as a basis outline a complete application which demonstrates how an ‘interface’ is defined and used in java.

<< interface>>Counter

void increment()void decrement()double read_val();

FloatCounter

float value;

void increment()void decrement()double read_val();

DoubleCounter

double value;

void increment()void decrement()double read_val();

Sep 2005 SDP-MSc Slide

78

Now Back to First Program

We will introduce a different form of Error Handling

Exception Handling

class Account{ private int accNo; private int balance; public Account(int No, int bal){ this.balance=bal;

this.accNo=No;}

public void credit(int amount){ balance+=amount;}

public bool debit(int amount){ if (amount > balance) return false;

else { balance = balance - amount;return true;}}

public void print_details(){ Console.Write("Details"+ ":"); Console.WriteLine("{0} Balance: {1}",accNo,balance);}}

Sep 2005 SDP-MSc Slide

80

public class Ex1{

public static void Main(){ Account a1 = new Account(1,100);

Account a2 = new Account(2,200); a1.credit(50); bool res1=a2.debit( 50); if (res1==false){Console.WriteLine("Error"); } a1.print_details(); a2.print_details(); }}

Sep 2005 SDP-MSc Slide

81

class MyException:Exception{public MyException(string s):base(s){}public MyException():base(){}

}

Exception Handling

Sep 2005 SDP-MSc Slide

82

class Account{ private int accNo; private int balance; public Account(int No, int bal){ this.balance=bal;

this.accNo=No;}

public void credit(int amount){ balance+= amount;}

public void debit(int amount){ if (amount > balance) throw new MyException();

else { balance = balance - amount;} }

:}

Sep 2005 SDP-MSc Slide

83

public class Ex1{

public static void Main(){ Account a1 = new Account(1,100);

Account a2 = new Account(2,200); a1.credit(50); try{ a2.debit( 450);} catch(Exception e){Console.WriteLine("Error"); } a1.print_details(); a2.print_details(); Console.Read();}}

Sep 2005 SDP-MSc Slide

84

Error

Account DetailsNo:1 Balance:150

Account DetailsNo:2 Balance:200

Sep 2005 SDP-MSc Slide

85

class Item{ private int lotno; private String bidder; private int bid;

public Item(int l,String bn, int b){lotno=l; bidder=bn; bid=b;}

public bool nextbid(String b_name, int amt){if (amt> bid){ bidder=b_name; bid=amt;

return true;}else return false;}

public void print_details(){ Console.WriteLine("Details:"); Console.WriteLine("Lot No: "+lotno); Console.WriteLine("Bidder Name:"+ bidder); Console.WriteLine("Bit Amount: "+ bid); } }

Q77. This Ex uses traditionalError Handling

-Rewrite usingExceptions

Continued…..

Sep 2005 SDP-MSc Slide

86

public class Q77{ public static void Main

Item item1=new Item(101,"NOBODY",0);int choice=1,amt;string name=" ";while (choice!=3){

Console.WriteLine("Menu:"); Console.WriteLine("1: Enter new Bid:"); Console.WriteLine("2: print Bid details:"); Console.WriteLine("3: Exit:");

Sep 2005 SDP-MSc Slide

87

Console.Write ("Enter Choice:"); string temp=Console.ReadLine();

choice=Convert.ToInt32(temp1);

switch(choice){ case 1: Console.Write ("Enter Amount:");

string temp1=Console.ReadLine(); amt=Convert.ToInt32(temp1);

Console.Write ("Enter Name:"); string name=Console.ReadLine(); bool res= item1.nextbid(name,amt); if (res==false) Console.Write ("Error Bid Too Low"); else Console.Write ln("Bid Accepted"); break;

case 2: item1.print_details(); break; case 3: break;}}}}

Sep 2005 SDP-MSc Slide

88

Aggregation

Sep 2005 SDP-MSc Slide

89

class Counter{ private int value;

public Counter(int v){ this.value = v;}public void update(int n)

{value=n;}public int read_value()

{ return this.value;}}

Sep 2005 SDP-MSc Slide

90

class Account{ protected Counter number; protected int balance; public Account(int n, int b){ number=new Counter(n);

balance=b;} public void update_number(int x){number.update(x);} public Counter read_num(){return number;} public void deposit(int amt) {this.balance+=amt;}

public void print(){ Console.Write("\nNo: {0}",number.read_value()); Console.WriteLine("Bal: {0}",balance);}

}

Sep 2005 SDP-MSc Slide

91

public class Ex1{

public static void Main(){ Account a1=new Account(10,100);

Account a2=new Account(20,200); a2.deposit(1); a2.print(); a1.update_number(30); a2.print();}

}

Sep 2005 SDP-MSc Slide

92

No: 20 Bal: 201

No: 30 Bal: 201

Sep 2005 SDP-MSc Slide

93

Aggregation

class Height {

private int feet, inches;

public Height( int f, int i ) { feet=f; inches = I;}

public int height_in_inches() { return (inches + feet*12); }

public void print(){

Console.Write(feet+”{0}\’-{1}\””,feet, inches);}

}

Sep 2005 SDP-MSc Slide

94

class Student {

private int age;

private String name;

private Height ht;

public Student( int a, String n, int f, int i )

{ht=new Height(f,i);

age=a; name=n; }

public void increment_age() { return age++; }

public void print(){

Console.Write (“Age:{0}\nName: {1}“,age, name;}

Console.Write (“\nHeight:”);

ht.print(); }

}

Sep 2005 SDP-MSc Slide

95

public class Test {

public static void Main(){

Student s1=new Student(20, “J.Smith”, 5,11);

int result = s1.read_height_in_inches();

Console.WriteLine(“Height in ins:{0}”, result);

s1.print();

}

Sep 2005 SDP-MSc Slide

96

Association

Sep 2005 SDP-MSc Slide

97

class Counter{ private int value;

public Counter(int v){ this.value = v;}public void update(int n)

{value=n;}public int read_value()

{ return this.value;}}

Sep 2005 SDP-MSc Slide

98

class Account{ protected Counter number; protected int balance; public Account(Counter no, int b){ number=no;

balance=b;} public void update_number(int x){number.update(x);} public Counter read_num(){return number;} public void deposit(int amt) {this.balance+=amt;} public void print(){

Console.Write("\nNo: {0}",number.read_value()); Console.WriteLine("Bal: {0}",balance);}

}

Sep 2005 SDP-MSc Slide

99

public class Ex21{

public static void Main(){ Counter c1=new Counter(10); Counter c2=new Counter(20);

Account a1=new Account(c1,100); Account a2=new Account(c2,200); a2.deposit(1); a2.print(); a1.update_number(30); a2.print();}

}

Sep 2005 SDP-MSc Slide

100

No: 20 Bal: 201

No: 30 Bal: 201

Sep 2005 SDP-MSc Slide

101

Association

class Height {

private int feet, inches;

public Height( int f, int i ) { feet=f; inches = I;}

public Height( ) { feet = 0; inches=i; }

public Height( Height h ){ feet= h.feet; inches= h.inches }

public int height_in_inches() { return (inches + feet*12); }

public void print(){

Console.Write(feet+”{0}\’-{1}\””,feet, inches);}

}

Sep 2005 SDP-MSc Slide

102

class Student {

private int age;

private String name;

private Height ht;

public Student( int a, String n, Height h )

{age=a; name=n; ht=h;}

public int read_height_in_inches() { return ht.height_in_inches(); }

public void print(){

Console.Write (“Age:{0}\nName: {1}“,age, name;}

Console.Write (“\nHeight:”);

ht.print(); }

}

Sep 2005 SDP-MSc Slide

103

public class Test {

public static void Main(){

Height h1=new Height(5,11);

Student s1=new Student(20, “J.Smith”, h1);

int result = s1.read_height_in_inches();

System.out.println(“Height in ins:”+result);

s1.print();

}

Sep 2005 SDP-MSc Slide

104

class Money{private int euro,cent;public Money(int e, int c){ this.euro=e; this.cent=c;}public void print(){ Console.WriteLine("E{0}.{1}"euro,cent);}public void reset(int x, int y){ euro=x; cent=y;}public boolean greater(int x, int y){ int val1_in_cent= y+x*100; int val2_in_cent= cent+euro*100;

if (val1_in_cent > val2_in_cent) return true;else return false;}

}

class Item{private int lotno;private String bidder;private Money bid;

Q78. Complete the following as an example of Aggregation

Continued…..

Sep 2005 SDP-MSc Slide

105

public class Q78{

public static void main(String[] args){Item item1=new Item(101,"NOBODY",0,0);int choice=1,amt1,amt2; String name=new String(" ");while (choice!=3){

System.out.println("Menu:");System.out.println("1: Enter new Bid:");System.out.println("2: print Bid details:");System.out.println("3: Exit:");choice=Console.readInt("Enter Choice:");switch(choice){

case 1: amt1=Console.readInt("Enter Amount in Euro:"); amt2=Console.readInt("Enter Amount in Cent:"); name=Console.readLine("Enter Name of bidder: "); try {item1.nextbid(name,amt1,amt2);

System.out.println("Bid Accepted");} catch(Exception e){ System.out.println("Error Bid Too Low");} break;

case 2: item1.print_details(); break;}}}}

Sep 2005 SDP-MSc Slide

106

class Money{private int euro,cent;public Money(int e, int c){ this.euro=e; this.cent=c;}public void print(){ System.out.println("E"+euro+"."+cent);}public void reset(int x, int y){ euro=x; cent=y;}public boolean greater(int x, int y){ int val1_in_cent= y+x*100; int val2_in_cent= cent+euro*100;

if (val1_in_cent > val2_in_cent) return true;else return false;}

}

class Item{private int lotno;private String bidder;private Money bid;

Q79. Now rewrite as an example of Association

Sep 2005 SDP-MSc Slide

107

Operator Overload

Sep 2005 SDP-MSc Slide

108

class Rational{ private int num, den; public Rational(){} public Rational(int n, int d){

this.num = n; this.den =d;} public static double translate(Rational r1){ return (double) r1.num/r1.den;} public static Rational mult(Rational r1, Rational r2)

{ Rational res=new Rational(); res.num= r1.num*r2.num; res.den= r1.den*r2.den;

return res;}public void print(){

Console.WriteLine("{0}/{1}",num,den); }}

Sep 2005 SDP-MSc Slide

109

public class Ex1{

public static void Main(){ Rational r1=new Rational(2,3); Rational r2=new Rational(1,2); Rational res1=Rational.mult(r1,r2); Console.Write("Result of mult: "); res1.print(); double res2=Rational.translate(r2); Console.Write("Result of Translation:{0}",res2); Console.Read();}

}

Sep 2005 SDP-MSc Slide

110

Sep 2005 SDP-MSc Slide

111

Now we will rewrite using

Operator Overload

Sep 2005 SDP-MSc Slide

112

class Rational{ private int num, den; public Rational(){} public Rational(int n, int d){

this.num = n; this.den =d;} public static explicit operator double (Rational r1) {return (double) r1.num/r1.den;} public static Rational operator*(Rational r1, Rational r2)

{ Rational res=new Rational(); res.num= r1.num*r2.num; res.den= r1.den*r2.den; return res;}

public void print(){Console.WriteLine("{0}/{1}",num,den); }

}

Sep 2005 SDP-MSc Slide

113

public class Ex1{

public static void Main(){ Rational r1=new Rational(2,3); Rational r2=new Rational(1,2); Rational res1=r1 * r2; Console.Write("Result of mult: "); res1.print(); double res2=(double) r2; Console.Write("Result of Translation:{0}",res2); Console.Read();}

}

Sep 2005 SDP-MSc Slide

114

: Rational res1=r1 * r2; Console.Write("Result of mult: "); res1.print();

:

Now to handle printing

Sep 2005 SDP-MSc Slide

115

class Rational{ private int num, den; :public static implicit operator float (Rational r1) {return (float) r1.num/r1.den;}

}

Sep 2005 SDP-MSc Slide

116

public class Ex1{

public static void Main(){Rational r1=new Rational(2,3); Rational r2=new Rational(1,2); Rational res1=r1 * r2; Console.Write("Result of mult: {0}", res1);

:

Sep 2005 SDP-MSc Slide

117

Create a complex number class with real and imagineryParts.

Include opeartor overload for * and +

Plus implicit and implicit casting

Q710. CompleX Numbers

Sep 2005 SDP-MSc Slide

118

Section 8 - UML Static Modelling

Section 8.1 Class Diagrams

Sep 2005 SDP-MSc Slide

119

The Class Diagram

Classname ORClassname

attribute: datatype

operation(args: type): type

Sep 2005 SDP-MSc Slide

120

The Class Diagram

Software

Course

Book

Details

Author

1 0..*

0..*

1..*

Sep 2005 SDP-MSc Slide

121

Finding Classes

• Use domain analysis as before

• Derive them from the use cases

• Look for data which must be stored or analyzed

• Are there external systems?

• Are there any devices under the control of the system?

• Are there any organizational parts?

Sep 2005 SDP-MSc Slide

122

Attributes

• Describe the state & characteristics of the object

• Must be typed, primitives like integers:– Real

– Boolean

– Point

– String

• Visibility must be: public (+),

private (-),

protected (#)

Sep 2005 SDP-MSc Slide

123

Example UML Class

Invoice

+ amount: Real+ date: Date=Current_date+ customer: String+ specification: String- administration: String=“unspecified”- number_of_invoices: Integer+ status: Status=unpaid {paid, unpaid}

Name, bold

Public, typed

Default value

Private

Class variable

property

Sep 2005 SDP-MSc Slide

124

Associations

Associations model Class relationships Associations should be named Use verbs from the problem domain Roles played by classes may also be named Associations have a cardinality

Sep 2005 SDP-MSc Slide

125

Association • One player may be a member of many teams

(United & Ireland)

•Player may leave one team & join another

TeamPlayer

**

Sep 2005 SDP-MSc Slide

126

Associations & Cardinality

Exactly One (default)

Zero or more

Optional (zero or one)

One or more

Numerically specified

Class1 Class1

Class

Class

Class

Class

Class

Association Name

*

0..1

1..*

3..8

Sep 2005 SDP-MSc Slide

127

Cardinality Examples

Employee

Name:String

Number:Integer

Dept

Name:String

VideoMember

Association Name

0..1 Rent *

HiresCustomer

Car

Reg: String

year: Integer

Sep 2005 SDP-MSc Slide

128

Class & Object Representation

Tsmith:Member

SpaceBalls: Video

VideoMember 0..1 Rent *

Rocky: Video

Sep 2005 SDP-MSc Slide

129

Association example

Insurance Policy

Insurance Contract

1 owns 0..*

refers to

Insurance

company

Customer

0..1

is expressed in

1

expresses an

has

0..1

refers to

1..* Note: Insurance Policy sent

after contract agreed

Sep 2005 SDP-MSc Slide

130

Association example expanded

Insurance Policy

Insurance Contract 1 owns 0..*

refers to

Insurance

company

Person

0..1

is expressed in

1

expresses an

has

0..1

refers to

1..*

husbandwife

Married to

insurer

Sep 2005 SDP-MSc Slide

131

Aggregation & Composition

• Special type of association

– “consists of”

– “contains”

– “part of”

Sep 2005 SDP-MSc Slide

132

Employee

Contract Aggregation

0..1 Delivery_Van

reg:String

Sep 2005 SDP-MSc Slide

133

Car

Service_record Aggregation

Owner

name:String

Sep 2005 SDP-MSc Slide

134

JFrame

TextField*

Listbox*

Button*

MenuItem*

Sep 2005 SDP-MSc Slide

135

Section 8.1 Exercises

8.1.1 Draw a Class Diagram for a company that employs many people. For each association between company and employee their is a contract.

The company has many divisions and each division has many departments. At any time an employee will be allocated to one department.

Sep 2005 SDP-MSc Slide

136

8.1.2

Outline a UML class that models the following proposed system. Make any assumptions you think appropriate. Include details of suitable attributes & methods.

“A boss/owner of a small retail outlet wants a computer system to automatehis admin procedures. He wants to record details about each employee, theirindividual employment contracts, employee sales records and details of the company cars some employees are supplied with. Details concerning allsuppliers and customers must also be recorded and a separate account ismaintained per customer. Its also necessary to keep track of all items in stock and the accounts for the company in general”.

Sep 2005 SDP-MSc Slide

137

Static Modelling 8.2

Section 8.2

Inheritance

Sep 2005 SDP-MSc Slide

138

Example

CarGeneral

Estate CoupeHatchbackSaloonSpecific

Sep 2005 SDP-MSc Slide

139

Java Implementation

Account

#amt:Real

+deposit()

ATMAccount

-pin:Integer

+withdraw()

Sep 2005 SDP-MSc Slide

140

Subclasses and Inheritance

class Account{

protected double amt;

public Account(int a) { }

:

} public class ATMAccount extends Account {

private int pin;

:

public void withdraw( int a) { amt = amt - a; } }

Sep 2005 SDP-MSc Slide

141

Concrete Subclasses

Car {abstract}

Estate CoupeHatchbackSaloon

Sep 2005 SDP-MSc Slide

142

Polymorphism

Shape

#colour:Colour

Draw(){abstract}

Square

Draw()

Circle

Draw()

Sep 2005 SDP-MSc Slide

143

Ways of showing constraints

Class A

Class B Class C Class D

{constraint 1,

constraint2}

Class A

Class B Class C Class D

{constraint 1,

constraint2}

Sep 2005 SDP-MSc Slide

144

Constrained Generalisation

• Generalisation may be:– Overlapping: a subclass can inherit from 2 classes, each of

which has a common parent

– Disjoint: opposite (default)

– Complete: no further class can inherit from this superclass

except those just specified

– Incomplete (default)

Sep 2005 SDP-MSc Slide

145

Overlapping Inheritance

Vehicle

Boat Car

Hovercraft

{overlapping}

Sep 2005 SDP-MSc Slide

146

Complete Inheritance

Person

Woman Man

{complete}

• No further class may inherit from Person in future

Sep 2005 SDP-MSc Slide

147

Exercises - Section 7.2

Ex8.2.1 Outline an Object Class Diagram for the following:

A company owns many computers. A company employs many employees. Most employees works on the same computer all the time. A few employees don’t use a computer at all.

The company has 2 types of computer: IBM and Apple. Some of the IBMs have Multimedia capability.

Sep 2005 SDP-MSc Slide

148

Ex7.2.2Using the UML methodology outline a Class Diagram that models the Banking System detailed below. Add attributes, operations, aggregations and associations as appropriate. Add additional classes as needed.

Can assume the Bank consists of Customer Accounts and an object describing the bank’s own finances.

These Customer Accounts can be of a General type or may be some sort of special Accounts with some additional parameters (e.g. Joint, Savings Account etc).Each Account is associated with a Customer object outlining customer details.

Each Customer may have more than one Account.

Sep 2005 SDP-MSc Slide

149

Ex7.2.3A company administration system records details concerning Employee detailsincluding name, number, salary, age etc. Employees are classified into various groups (Managers, Craftsmen etc) for administration purposes.Operations on Employees typically updates details like age and salary etc.Each employee has a contact. Work is organised into Projects, each projectHas a single manager but several workers in other categories. An employeecan be allocated to a maximum of two projects.

Using this application, adding more details to the requirements as needed, describe in detail the complete UML Class Diagram.

Sep 2005 SDP-MSc Slide

150

Appendix 1- Chapter 7

Aggregation & Association

Sep 2005 SDP-MSc Slide

151

Aggregation

class Height {

private int feet, inches;

public Height( int f, int i ) { feet=f; inches = I;}

public Height( ) { feet = 0; inches=i; }

public Height( Height h ){ feet= h.feet; inches= h.inches }

public int height_in_inches() { return (inches + feet*12); }

public void print(){ System.out.print(feet+”’-”+inches+”\” ”);}

}

Sep 2005 SDP-MSc Slide

152

class Student {

private int age;

private String name;

private Height ht;

public Student( int a, String n, int f, int i )

{ht=new Height(f,i);

age=a; name=n; }

public int read_height_in_inches() { return ht.height_in_inches(); }

public void print(){

System.out.print(“Age:”+age + “\nName: “+ name;}

System.out.print(“\nHeight:”);

ht.print(); }

}

Sep 2005 SDP-MSc Slide

153

public class Test {

public static void main(String[] args){

Student s1=new Student(20, “J.Smith”, 5,11);

int result = s1.read_height_in_inches();

System.out.println(“Height in ins:”+result);

s1.print();

}

Sep 2005 SDP-MSc Slide

154

Association

class Height {

private int feet, inches;

public Height( int f, int i ) { feet=f; inches = I;}

public Height( ) { feet = 0; inches=i; }

public Height( Height h ){ feet= h.feet; inches= h.inches }

public int height_in_inches() { return (inches + feet*12); }

public void print(){ System.out.print(feet+”’-”+inches+”\” ”);}

}

Sep 2005 SDP-MSc Slide

155

class Student {

private int age;

private String name;

private Height ht;

public Student( int a, String n, Height h )

{age=a; name=n; ht=h;}

public int read_height_in_inches() { return ht.height_in_inches(); }

public void print(){

System.out.print(“Age:”+age + “\nName: “+ name;}

System.out.print(“\nHeight:”);

ht.print(); }

}

Sep 2005 SDP-MSc Slide

156

public class Test {

public static void main(String[] args){

Height h1=new Height(5,11);

Student s1=new Student(20, “J.Smith”, h1);

int result = s1.read_height_in_inches();

System.out.println(“Height in ins:”+result);

s1.print();

}

Sep 2005 SDP-MSc Slide

157

Appendix 2 - Abstract Class

In it will now look at 4 versions of the same program:

1) Normal Inheritance

2) abstract function

3) abstract class

4) interface

See Appendix 1 - Additional Examples

Sep 2005 SDP-MSc Slide

158

class Rat{ // Version 1 -Normal Inheritance

protected int num, den;

public Rat(int n, int d){num=n; den=d;}

public int readnum() {return num;}

public void print() {System.out.println("Rat: "+num+"/"+den);}

}

class RatSign extends Rat {

private char sign;

RatSign(char s, int n, int d){ super(n,d); sign=s;}

public int readden(){return den;}

public void print(){System.out.println(sign+num+"/"+den);}

}

Sep 2005 SDP-MSc Slide

159

public class Version1{

public static void main(String[] args){

Rat rArray[] = new Rat[2];

Rat r = new Rat(2,3);

RatSign rs = new RatSign('-', 3, 4);

rArray[0] = r;

rArray[1] = rs;

for( int i = 0; i < rArray.length; i++ )

rArray[i].print();

}

}

Sep 2005 SDP-MSc Slide

160

abstract class Rat{ // Version 2: Abstract function

protected int num, den;

public Rat(int n, int d){num=n; den=d;}

public int readnum() {return num;}

abstract public void print();

}

class RatSign extends Rat {

private char sign;

RatSign(char s, int n, int d){ super(n,d); sign=s;}

public int readden(){return den;}

public void print(){System.out.println(sign+num+"/"+den);}

}

Sep 2005 SDP-MSc Slide

161

public class Version2{

public static void main(String[] args){

Rat rArray[] = new Rat[2];

// Rat r = new Rat(2,3); - not allowed RatSign rs2 = new RatSign('+',2,3);

RatSign rs = new RatSign('-', 3, 4);

rArray[0] = rs2;

rArray[1] = rs;

for( int i = 0; i < rArray.length; i++ )

rArray[i].print();

}

}

Sep 2005 SDP-MSc Slide

162

abstract class Rat{ // Version 3: abstract class

abstract public int readnum();

abstract public void print();

}

class RatSign extends Rat {

private int num, den;

private char sign;

RatSign(char s, int n, int d){ num=n; den=d; sign=s;}

public int readnum(){return num;}

public int readden(){return den;}

public void print(){System.out.println(sign+num+"/"+den);}

}

Sep 2005 SDP-MSc Slide

163

public class Version3{

public static void main(String[] args){

Rat rArray[] = new Rat[2];

RatSign rs2 = new RatSign('+',2,3);

RatSign rs = new RatSign('-', 3, 4);

rArray[0] = rs2;

rArray[1] = rs;

for( int i = 0; i < rArray.length; i++ )

rArray[i].print();

}

}

Sep 2005 SDP-MSc Slide

164

interface Rat{ // Version 4: interface

public int readnum();

public void print();

}

class RatSign implements Rat {

private int num, den;

private char sign;

RatSign(char s, int n, int d){ num=n; den=d; sign=s;}

public int readnum(){return num;}

public int readden(){return den;}

public void print(){System.out.println(sign+num+"/"+den);}

}

Sep 2005 SDP-MSc Slide

165

public class Version4{

public static void main(String[] args){

Rat rArray[] = new Rat[2];

RatSign rs2 = new RatSign('+',2,3);

RatSign rs = new RatSign('-', 3, 4);

rArray[0] = rs2;

rArray[1] = rs;

for( int i = 0; i < rArray.length; i++ )

rArray[i].print();

}

}

Another Example- Interface

• public interface Value { public void setValue( float c ); public float readValue(); public void printValue( ); }

• public class Intvalue implements Value { private int val; public void setValue( float c ){val=(float) c;} public float readValue(){return val;} public void printValue( )

{ System.out.print(“Value:” + val);}

}

Sep 2005 SDP-MSc Slide

167

Defining an Interface• public class Floatvalue implements Value {

private float val;

public void setValue( float c ){val= c;} public float readValue(){return val;} public void printValue( ) {System.out.print(“Val:” + val);} }

• public class Test{

public static void main(String[] args){

Value[] values = new Value[2]; values[0]=new Intvalue(); values[1]=new Floatvalue() ); for( int i = 0; i < values.length; i++ ) { values[i].setValue(i+2);

values[i].printValue();}} }