Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sep 2005 SDP-MSc Slide 1 Section 7 Object Oriented Programming.

Similar presentations


Presentation on theme: "Sep 2005 SDP-MSc Slide 1 Section 7 Object Oriented Programming."— Presentation transcript:

1 Sep 2005 SDP-MSc Slide 1 Section 7 Object Oriented Programming

2 Sep 2005 SDP-MSc Slide 2 Object Oriented Programming Section 7.1 Class Definition

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

4 public class Ex1{ public static void Main(){ Counter c1; c1=new Counter(6, "Days"); c1.increment(); int res=c1.read_value(); Console.WriteLine("Value: {0}",res); }

5 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

6 Sep 2005 SDP-MSc Slide 6

7 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

8 public class Ex1{ public static void Main(){ Counter c1; c1=new Counter(6, "Days"); c1.NUMBER=9; c1.increment(); int res=c1.NUMBER; Console.WriteLine("Value: {0}",res); } Properties

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

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

11 Sep 2005 SDP-MSc Slide 11 Account Details No:1 Balance:150 Account Details No:2 Balance:200

12 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

13 Sep 2005 SDP-MSc Slide 13 Alternative Version using properties get, set

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

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

16 Sep 2005 SDP-MSc Slide 16 Indexers Array type indexing of a class object

17 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;} }} :

18 Sep 2005 SDP-MSc Slide 18 public class Ex1{ public static void Main(){ Vector v =new Vector(); v[1]=9; // set Console.WriteLine("value={0}",v[1]); // get }

19 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++;} }:

20 Sep 2005 SDP-MSc Slide 20 : public void print_LList(){ Console.WriteLine(""); for(int i=0;i<count;i++){ Console.WriteLine(" {0}",list[i]); }

21 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"); :

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

23 Sep 2005 SDP-MSc Slide 23 Version 2 of Account Class - static variables

24 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;} : }

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

26 Sep 2005 SDP-MSc Slide 26 Account Details No:1 Balance:150 Account Details No:2 Balance:200 Total no of Accounts:2

27 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?

28 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

29 Sep 2005 SDP-MSc Slide 29 Now Version 3: Inheritance

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

31 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 = '-';} }

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

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

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

35 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; :

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

37 Sep 2005 SDP-MSc Slide 37

38 Sep 2005 SDP-MSc Slide 38 Section 1 Object Oriented Programming (Revision)

39 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++;} }:

40 Sep 2005 SDP-MSc Slide 40 : public void print_LList(){ Console.WriteLine(""); for(int i=0;i<count;i++){ Console.WriteLine(" {0}",list[i]); }

41 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"); :

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

43 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(){ :

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

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

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

47 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

48 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

49 Sep 2005 SDP-MSc Slide 49 Next Version4: Polymorphism (Dynamic Binding)

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

51 Sep 2005 SDP-MSc Slide 51 public class Ex1{ public static void Main(){ Base b=new Base(); b.f1(); b.f2(); Console.Read(); }

52 Sep 2005 SDP-MSc Slide 52

53 Sep 2005 SDP-MSc Slide 53 public class Ex1{ public static void Main(){ Base b=new Derv(); b.f1(); b.f2(); Console.Read(); }

54 Sep 2005 SDP-MSc Slide 54

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

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

57 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){ :

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

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

60 Sep 2005 SDP-MSc Slide 60 Account Details No:1 Balance:150 Pin: 2222 Account Details No:2 Balance:2000

61 Sep 2005 SDP-MSc Slide 61 Version 5: Abstract Classes

62 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

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

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

65 Sep 2005 SDP-MSc Slide 65 Account Details No:1 Balance:150 Pin: 2222 Account Details No:2 Balance:200 Pin: 3333

66 pure abstract class

67 abstract class Counter{ public abstract void increment(); public abstract void decrement(); public abstract int read_value(); }

68 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 = '-';} }

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

70 interfaces

71 interface Counter{ void increment(); void decrement(); int read_value(); }

72 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 = '-';} }

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

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

75 Sep 2005 SDP-MSc Slide 75 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

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

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

78 Sep 2005 SDP-MSc Slide 78 Now Back to First Program We will introduce a different form of Error Handling Exception Handling

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

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

81 Sep 2005 SDP-MSc Slide 81 class MyException:Exception{ public MyException(string s):base(s){} public MyException():base(){} } Exception Handling

82 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;} } : }

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

84 Sep 2005 SDP-MSc Slide 84 Error Account Details No:1 Balance:150 Account Details No:2 Balance:200

85 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 traditional Error Handling -Rewrite using Exceptions Continued…..

86 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:");

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

88 Sep 2005 SDP-MSc Slide 88 Aggregation

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

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

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

92 Sep 2005 SDP-MSc Slide 92 No: 20 Bal: 201 No: 30 Bal: 201

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

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

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

96 Sep 2005 SDP-MSc Slide 96 Association

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

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

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

100 Sep 2005 SDP-MSc Slide 100 No: 20 Bal: 201 No: 30 Bal: 201

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

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

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

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

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

106 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

107 Sep 2005 SDP-MSc Slide 107 Operator Overload

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

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

110 Sep 2005 SDP-MSc Slide 110

111 Sep 2005 SDP-MSc Slide 111 Now we will rewrite using Operator Overload

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

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

114 Sep 2005 SDP-MSc Slide 114 : Rational res1=r1 * r2; Console.Write("Result of mult: "); res1.print(); : Now to handle printing

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

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

117 Sep 2005 SDP-MSc Slide 117 Create a complex number class with real and imaginery Parts. Include opeartor overload for * and + Plus implicit and implicit casting Q710. CompleX Numbers

118 Sep 2005 SDP-MSc Slide 118 Section 8 - UML Static Modelling Section 8.1 Class Diagrams

119 Sep 2005 SDP-MSc Slide 119 The Class Diagram Classname OR Classname attribute: datatype operation(args: type): type

120 Sep 2005 SDP-MSc Slide 120 The Class Diagram Software Course Book Details Author 1 0..* 0..* 1..*

121 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?

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

123 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

124 Sep 2005 SDP-MSc Slide 124 Associations u Associations model Class relationships u Associations should be named u Use verbs from the problem domain u Roles played by classes may also be named u Associations have a cardinality

125 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 Team Player * *

126 Sep 2005 SDP-MSc Slide 126 Associations & Cardinality Exactly One (default) Zero or more Optional (zero or one) One or more Numerically specified Class1 Class Association Name * 0..1 1..* 3..8

127 Sep 2005 SDP-MSc Slide 127 Cardinality Examples Employee Name:String Number:Integer Dept Name:String Video Member Association Name 0..1 Rent * Hires Customer Car Reg: String year: Integer

128 Sep 2005 SDP-MSc Slide 128 Class & Object Representation Tsmith:Member SpaceBalls: Video Video Member 0..1 Rent * Rocky: Video

129 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

130 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..* husband wife Married to insurer

131 Sep 2005 SDP-MSc Slide 131 Aggregation & Composition Special type of association – “consists of” – “contains” – “part of”

132 Sep 2005 SDP-MSc Slide 132 Employee Contract Aggregation 0..1 Delivery_Van reg:String

133 Sep 2005 SDP-MSc Slide 133 Car Service_record Aggregation Owner name:String

134 Sep 2005 SDP-MSc Slide 134 JFrame TextField * Listbox * Button * MenuItem *

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

136 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 automate his admin procedures. He wants to record details about each employee, their individual employment contracts, employee sales records and details of the company cars some employees are supplied with. Details concerning all suppliers and customers must also be recorded and a separate account is maintained per customer. Its also necessary to keep track of all items in stock and the accounts for the company in general”.

137 Sep 2005 SDP-MSc Slide 137 Static Modelling 8.2 Section 8.2 Inheritance

138 Sep 2005 SDP-MSc Slide 138 Example Car General EstateCoupeHatchbackSaloon Specific

139 Sep 2005 SDP-MSc Slide 139 Java Implementation Account #amt:Real +deposit() ATMAccount -pin:Integer +withdraw()

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

141 Sep 2005 SDP-MSc Slide 141 Concrete Subclasses Car {abstract } EstateCoupeHatchbackSaloon

142 Sep 2005 SDP-MSc Slide 142 Polymorphism Shape #colour:Colour Draw(){abstract} Square Draw() Circle Draw()

143 Sep 2005 SDP-MSc Slide 143 Ways of showing constraints Class A Class B Class CClass D {constraint 1, constraint2} Class A Class B Class CClass D {constraint 1, constraint2 }

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

145 Sep 2005 SDP-MSc Slide 145 Overlapping Inheritance Vehicle Boat Car Hovercraft {overlapping}

146 Sep 2005 SDP-MSc Slide 146 Complete Inheritance Person Woman Man {complete} No further class may inherit from Person in future

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

148 Sep 2005 SDP-MSc Slide 148 Ex7.2.2 Using 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.

149 Sep 2005 SDP-MSc Slide 149 Ex7.2.3 A company administration system records details concerning Employee details including 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 project Has a single manager but several workers in other categories. An employee can 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.

150 Sep 2005 SDP-MSc Slide 150 Appendix 1- Chapter 7 Aggregation & Association

151 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+”\” ”);} }

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

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

154 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+”\” ”);} }

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

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

157 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

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

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

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

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

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

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

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

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

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

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


Download ppt "Sep 2005 SDP-MSc Slide 1 Section 7 Object Oriented Programming."

Similar presentations


Ads by Google