Object Oriented Programming - PowerPoint PPT Presentation

About This Presentation
Title:

Object Oriented Programming

Description:

Console.WriteLine('2: Decrement'); Console.WriteLine('3: Read Value' ... case 2: c1.decrement(); break; case 3: int res=c1.read_value ... – PowerPoint PPT presentation

Number of Views:38
Avg rating:3.0/5.0
Slides: 168
Provided by: dra77
Category:

less

Transcript and Presenter's Notes

Title: Object Oriented Programming


1
Section 7
Object Oriented Programming
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 c1new
Counter(6, "Days") c1.increment()
c1.increment() int resc1.read_value()
Console.WriteLine("Value 0",res)
5
Alternative Test Fn
public class Ex1 public static void Main()
Counter c1new Counter(6,"Days Worked") int
choice0 while (choice
!3) Console.WriteLine("") Console.WriteLi
ne("1 Increment") Console.WriteLine("2 Read
Value") Console.WriteLine("3
Exit") Console.Write("Enter Choice
") string tempConsole.ReadLine()
choiceConvert.ToInt32(temp) switch(choice)
case 1 c1.increment() break
case 2 int resc1.read_value()
Console.WriteLine(" 0",res)
break
6
(No Transcript)
7
Properties
Allows Read/Write access to member data class
Counter private string name
private int number public int
NUMBER get return number set
numbervalue // 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
8
Properties
public class Ex1 public static void Main()
Counter c1 c1new
Counter(6, "Days") c1.NUMBER9
c1.increment() c1.increment() int
resc1.NUMBER Console.WriteLine("Value
0",res)
9
class Account private int accNo
private int balance
public Account(int No, int bal)
this.balancebal
this.accNoNo public int getAccNo()return
accNo public int getBalance() return
balance public void credit(int amount)
balanceamount public void
print_details() System.out.print("\nAcco
unt Details \nNo)
System.out.println(accNo" Balance"balance)

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
Account Details No1 Balance150 Account
Details No2 Balance200
12
public class Ex1 public static void Main()
Account a1 new Account(1,100) int
amt0, choice0 while (choice
!3) Console.WriteLine("") Console.WriteLin
e("1 Deposit") Console.WriteLine("2 Check
Balance") Console.WriteLine("3
Exit") Console.Write("Enter Choice")
choiceConvert.ToInt32(Console.Rea
dLine()) switch(choice) case 1
Console.WriteLine("Enter Amount")

amtConvert.ToInt32(Console.ReadLine())
a1.credit(amt) break case 2
a1.print_details() break


Alternative Test Fn
13
Alternative Version using properties
get, set
14
class Account private int accNo
private int balance
public Account(int No, int bal)
this.balancebal
this.accNoNo public int Account_No
get return accNo
set accNo value public int getBalance
getreturn balance //
only read access public void credit(int
amount) balanceamount public void
print_details() Console.Write("Details"
"") Console.WriteLine("0 Balance
1",accNo,balance)
15
public class Ex1 public static void Main()
Account a1 new Account(1,100)
Account a2 new Account(2,200)
a1.Account_No678 // set
int resa1.getBalance // get
Console.WriteLine("a1 bal0",res)
a1.print_details() a2.print_details()

16
Indexers
Array type indexing of a class object
17
class Vector private int count4 private
int arr3,3,6,7 public int thisint
index get if (index lt count) return
arrindex else return
0 set arrindexvalue
18
public class Ex1 public static void
Main() Vector v new Vector() v19

// set Console.WriteLine("value0",v1) //
get
19
class LList private int list private int
count private int size public LList(int
s) this.sizes
this.count0
this.listnew ints public void insert(int
v) if (countltsize)
listcountv count
20
public void print_LList()
Console.WriteLine("") for(int
i0iltcounti) Console.WriteLine("
0",listi)
21
public class Ex1 public static void Main()
LList s new LList(5) int val0,
choice0 while (choice !3)
Console.WriteLine("") Console.WriteLine("
1 Insert") Console.WriteLine("2 Print
Stack") Console.WriteLine("3 Exit")

22
Console.Write("Enter
Choice")
choiceConvert.ToInt32(Console.ReadLine()) swi
tch(choice) case 1
Console.Write("Enter Value")
valConvert.ToInt32(Console.
ReadLine()) s.insert(val)
break case 2
s.print_LList() break


23
  • Version 2 of Account Class
  • - static variables

24
class Account private int accNo
private int balance
private static int count0
public Account(int bal)
this.balancebal this.accNocount
public int getAccNo()return accNo public
int getBalance() return balance
public static int read_count()return count
public void credit(int amount)
balanceamount
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 totalAccount.read_co
unt() Console.WriteLine("no of
Accounts0",total)
26
Account Details No1 Balance150 Account
Details No2 Balance200 Total no of
Accounts2
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
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 gt current
bid
Online Auction
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 c1new MyCounter(6,"Days
Worked",'') int choice0 while
(choice !4) Console.WriteLine("") Console.W
riteLine("1 Increment") Console.WriteLine("2
Decrement") Console.WriteLine("3 Read
Value") Console.WriteLine("4
Exit") Console.Write("Enter Choice
") string tempConsole.ReadLine() choiceConve
rt.ToInt32(temp) switch(choice) case 1
c1.increment() break case 2
c1.decrement() break case 3 int
resc1.read_value()
Console.WriteLine(" 0",res) break
33
class Account private int accNo
protected int balance
public Account(int No, int bal)
this.balancebal
this.accNoNo public int getAccNo()return
accNo public int getBalance() return
balance public void credit(int amount)
balanceamount public void
print_details() Console.Write("Details"
"") Console.WriteLine("0 Balance
1",accNo,balance)
34
class ATMaccount Account private int
pin public ATMaccount(int n,int bal, int
pin)base(n,bal) this.pinpin
public bool debit(int amount)
if (amount gt balance) return false else
balance balance - amount return
true public bool pinOK(int pin)
if (this.pinpin) return
true else return
false new public void print_details()
base.print_details()
Console.WriteLine("Pin 0",pin)
35
public class Ex1 public static void Main()
ATMaccount a1 new ATMaccount(3214, 100,
2222) Console.Write("Enter Pin")
int pinConvert.ToInt32(Console.ReadLine())
while (a1.pinOK(pin)false)
Console.Write("Enter Pin")
pinConvert.ToInt32(Console.ReadLine())
int amt0, choice0

36

while (choice !4) Console.WriteLine("") Co
nsole.WriteLine("1 Deposit") Console.WriteLine(
"2 Withdraw") Console.WriteLine("3 Check
Balance") Console.WriteLine("4
Exit") Console.Write("Enter Choice")
choiceConvert.ToInt32(Console.ReadLine()) sw
itch(choice) case 1 Console.Write("Enter
Amount ")
amtConvert.ToInt32(Console.ReadLine())
a1.credit(amt) break case 2
Console.Write("Enter Amount ")
amtConvert.ToInt32(Console.ReadLin
e()) a1.debit(amt) break
case 3 a1.print_details() break

37
(No Transcript)
38
Section 1
Object Oriented Programming
(Revision)
39
class LList private int list private int
count private int size public LList(int
s) this.sizes
this.count0
this.listnew ints public void insert(int
v) if (countltsize)
listcountv count
40
public void print_LList()
Console.WriteLine("") for(int
i0iltcounti) Console.WriteLine("
0",listi)
41
public class Ex1 public static void Main()
LList s new LList(5) int val0,
choice0 while (choice !3)
Console.WriteLine("") Console.WriteLine("
1 Insert") Console.WriteLine("2 Print
Stack") Console.WriteLine("3 Exit")

42
Console.Write("Enter
Choice")
choiceConvert.ToInt32(Console.ReadLine()) swi
tch(choice) case 1
Console.Write("Enter Value")
valConvert.ToInt32(Console.
ReadLine()) s.insert(val)
break case 2
s.print_LList() break


43
class LList protected int list protected
int count private int size public
LList(int s) this.sizes
this.count0
this.listnew ints public void
insert(int v) if (countltsize)
listcountv
count public void print_LList()
44
class Stack LList public Stack(int
s)base(s) public int remove(int v)
int res-1 if (count gt0)
reslistcount-1 count-- return
res
45
public class Ex1 public static void Main()
Stack s new Stack(5) int val0, choice0
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")
choiceConvert.ToInt32(Console.ReadLine())

46
switch(choice)
case 1 Console.Write("Enter Value")
valConvert.ToInt32(Console.Read
Line()) s.insert(val)
break case 2 vals.remove(val)
if (valgt0)
Console.Write("0 Deleted",val)
break case 3 s.print_LList() break


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
Q74. Complete the following class main
menu class Exp_Item Item // bid only
accepted if gt 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
Next Version4 Polymorphism (Dynamic Binding)
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
public class Ex1 public static void
Main() Base bnew Base() b.f1() b.f2()
Console.Read()
52
(No Transcript)
53
public class Ex1 public static void
Main() Base bnew Derv() b.f1() b.f2()
Console.Read()
54
(No Transcript)
55
class Account private int accNo
protected int balance
public Account(int No, int bal)
this.balancebal
this.accNoNo public int getAccNo()return
accNo public int getBalance() return
balance public void credit(int amount)
balanceamount 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
class ATMaccount Account private int
pin public ATMaccount(int n,int bal, int
pin)base(n,bal) this.pinpin
public override bool debit(int amount)
Console.WriteLine("derv") if
(amount gt balance) return false else
balance balance - amount
return true public override bool
pinOK(int pin) if (this.pinpin)
return true else
return false public override void
print_details()
base.print_details()
Console.WriteLine("Pin 0",pin)
57
public class Ex1 public static void Main()
Account a1 new ATMaccount(3214, 100, 2222)
Console.Write("Enter Pin") int
pinConvert.ToInt32(Console.ReadLine())
while (a1.pinOK(pin)false)
Console.Write("Enter Pin")
pinConvert.ToInt32(Console.ReadLine())
int amt0, choice0 while (choice !4)

58
switch(choice) case 1 Console.Write("Enter
Amount ")
amtConvert.ToInt32(Console.ReadLine())
a1.credit(amt) break case 2
Console.Write("Enter Amount ")
amtConvert.ToInt32(Console.ReadLine())
a1.debit(amt) break
case 3 a1.print_details()
break
59
public class Ex2 public static void Main()
Account array new Account2
array0 new ATMaccount(3210,100,2222)
array1 new Account(3211,200) if
(array0.pinOK(2222)true)
array0.credit(50) for(int i0 ilt2i)
arrayi.print_details()
60
Account Details No1 Balance150 Pin
2222 Account Details No2 Balance2000
61
Version 5 Abstract Classes
62
abstract classes interfaces
abstract class Account private int accNo
protected
int balance public Account(int No,
int bal) this.balancebal
this.accNoNo public int
getAccNo()return accNo public int
getBalance() return balance public void
credit(int amount) balanceamount
public abstract bool pinOK(int pin)
public abstract bool debit(int amount)
63
class ATMaccount Account private int
pin public ATMaccount(int n,int bal, int
pin)base(n,bal) this.pinpin
public override bool debit(int amount)
Console.WriteLine("derv") if
(amount gt balance) return false else
balance balance - amount
return true public override bool
pinOK(int pin) if (this.pinpin)
return true else
return false public override void
print_details()
base.print_details()
Console.WriteLine("Pin 0",pin)
64
public class Ex2 public static void Main()
Account array new Account2
array0 new ATMaccount(3210,100,2222)
array1 new ATMaccount(3211,200,3333) if
(array0.pinOK(2222)true)
array0.credit(50) for(int i0 ilt2i)
arrayi.print_details()
65
Account Details No1 Balance150 Pin
2222 Account Details No2 Balance200 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 c1new MyCounter(6,"Days
Worked",'') int choice0 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 tempConsole.ReadLine()
choiceConvert.ToInt32(temp) switch(choice)
case 1 c1.increment() break
case 2 c1.decrement() break
case 3 int resc1.read_value()
Console.WriteLine(" 0",res)
break
70
interfaces
71
interface Counter void
increment() void
decrement() int read_value()
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
public class Ex1 public static void Main()
MyCounter c1new MyCounter(6,"Days
Worked",'') int choice0 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 tempConsole.ReadLine()
choiceConvert.ToInt32(temp) switch(choice)
case 1 c1.increment() break
case 2 c1.decrement() break
case 3 int resc1.read_value()
Console.WriteLine(" 0",res)
break
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
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
public class Q75
public static void main(String args)
Counter c1new Counter2 Steps_of_one
s1new Steps_of_one(5) Steps_of_two
s2new Steps_of_two(5) c10s1
c11s2 int choice0,
index0 while (choice!4) Console.WriteLine(
"") Console.WriteLine("1 Increment") Conso
le.WriteLine("2 Decrement") Console.WriteLine(
"3 Read Value") Console.WriteLine("4
Exit") Console.Write("Enter Choice
") string tempConsole.ReadLine()
choiceConvert.ToInt32(temp)
Console.Write(" Enter Counter Index
(0 or 1") string temp1Console.ReadLine()
choiceConvert.ToInt32(temp1) swit
ch(choice) case 1 c1index.increment()
break case 2 c1index.decrement()
break case 3 System.out.println("Value "
c1index.readvalue())
break
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
Exception Handling
Now Back to First Program We will introduce a
different form of Error Handling
79
class Account private int accNo
private int balance
public Account(int No, int bal)
this.balancebal
this.accNoNo public void credit(int
amount) balanceamount public bool
debit(int amount) if
(amount gt balance) return false else
balance balance - amount return true
public void print_details()
Console.Write("Details" "")
Console.WriteLine("0 Balance
1",accNo,balance)
80
public class Ex1 public static void Main()
Account a1 new Account(1,100)
Account a2 new Account(2,200)
a1.credit(50) bool res1a2.debit( 50)
if (res1false)Console.WriteLine("Error")
a1.print_details()
a2.print_details()
81
Exception Handling
class MyExceptionException public
MyException(string s)base(s) public
MyException()base()
82
class Account private int accNo
private int balance public
Account(int No, int bal) this.balancebal
this.accNoNo public void
credit(int amount) balance amount public
void debit(int amount) if
(amount gt balance) throw new MyException()
else balance balance - amount

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
Error Account Details No1 Balance150 Account
Details No2 Balance200
85
class Item private int lotno
private String bidder private int
bid public Item(int l,String bn, int
b) lotnol bidderbn bidb public bool
nextbid(String b_name, int amt) if (amtgt bid)
bidderb_name
bidamt 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
public class Q77
public static void Main Item
item1new Item(101,"NOBODY",0) int
choice1,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
Console.Write
("Enter Choice") string
tempConsole.ReadLine()
choiceConvert.ToInt32(temp1) switch(choice)
case 1 Console.Write ("Enter
Amount")
string temp1Console.ReadLine()

amtConvert.ToInt32(temp1)
Console.Write
("Enter Name") string
nameConsole.ReadLine() bool res
item1.nextbid(name,amt) if
(resfalse) Console.Write ("Error Bid Too
Low") else Console.Write
ln("Bid Accepted") break
case 2 item1.print_details() break
case 3 break
88
Aggregation
89
class Counter private int
value public Counter(int v)
this.value v public void update(int n)

valuen public int read_value()
return this.value
90
class Account protected Counter number
protected int balance public Account(int
n, int b) numbernew Counter(n)
balanceb public void
update_number(int x)number.update(x)
public Counter read_num()return number
public void deposit(int amt)
this.balanceamt publ
ic void print() Console.Write("\nNo
0",number.read_value())
Console.WriteLine("Bal 0",balance)
91
public class Ex1 public static void Main()
Account a1new Account(10,100)
Account a2new Account(20,200)
a2.deposit(1) a2.print()
a1.update_number(30) a2.print()
92
No 20 Bal 201 No 30
Bal 201
93
Aggregation
class Height private int feet,
inches public Height( int f, int i )
feetf inches I public int
height_in_inches() return (inches feet12)
public void print()
Console.Write(feet0\-1\,feet,
inches)
94
class Student private int age private
String name private Height ht public
Student( int a, String n, int f, int i )
htnew Height(f,i)
agea namen public void
increment_age() return age public
void print()
Console.Write (Age0\nName 1,age, name
Console.Write
(\nHeight)
ht.print()
95
public class Test public static void Main()
Student s1new Student(20,
J.Smith, 5,11) int result
s1.read_height_in_inches()
Console.WriteLine(Height in ins0, result)
s1.print()
96
Association
97
class Counter private int
value public Counter(int v)
this.value v public void update(int n)

valuen public int read_value()
return this.value
98
class Account protected Counter number
protected int balance public
Account(Counter no, int b) numberno
balanceb public
void update_number(int x)number.update(x)
public Counter read_num()return number
public void deposit(int amt)
this.balanceamt
public void print() Console.Write("\nNo
0",number.read_value())
Console.WriteLine("Bal 0",balance)
99
public class Ex21 public static void
Main() Counter c1new Counter(10) Counter
c2new Counter(20) Account a1new
Account(c1,100) Account a2new
Account(c2,200) a2.deposit(1)
a2.print() a1.update_number(30)
a2.print()
100
No 20 Bal 201 No 30
Bal 201
101
Association
class Height private int feet,
inches public Height( int f, int i )
feetf inches I public Height( )
feet 0 inchesi public Height(
Height h ) feet h.feet inches h.inches
public int height_in_inches()
return (inches feet12) public
void print() Console.Write(feet0
\-1\,feet, inches)
102
class Student private int age private
String name private Height ht public
Student( int a, String n, Height h )
agea namen hth public
int read_height_in_inches() return
ht.height_in_inches() public void
print()
Console.Write (Age0\nName 1,age, name
Console.Write
(\nHeight)
ht.print()
103
public class Test public static void Main()
Height h1new Height(5,11)
Student s1new Student(20, J.Smith,
h1) int result
s1.read_height_in_inches()
System.out.println(Height in insresult)
s1.print()
104
Q78. Complete the following as an example of
Aggregation
class Money private int euro,cent public
Money(int e, int c) this.euroe
this.centc public void print()
Console.WriteLine("E0.1"euro,cent) public
void reset(int x, int y) eurox
centy public boolean greater(int x, int y)
int val1_in_cent yx100 int
val2_in_cent centeuro100 if (val1_in_cent gt
val2_in_cent) return true else

return false class Item private int
lotno private String bidder private Money bid
Continued..
105
public class Q78
public static void main(String
args) Item item1new Item(101,"NOBODY",0,0)
int choice1,amt1,amt2 String
namenew String(" ") while
(choice!3) System.out.println("Menu") Sy
stem.out.println("1 Enter new Bid") System.o
ut.println("2 print Bid details") System.out
.println("3 Exit") choiceConsole.readInt("E
nter Choice") switch(choice)
case 1 amt1Console.readInt("Enter Amount
in Euro") amt2Console.readInt("Enter
Amount in Cent") nameConsole.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
Q79. Now rewrite as an example of Association
class Money private int euro,cent public
Money(int e, int c) this.euroe
this.centc public void print()
System.out.println("E"euro"."cent) public
void reset(int x, int y) eurox
centy public boolean greater(int x, int y)
int val1_in_cent yx100 int
val2_in_cent centeuro100 if (val1_in_cent gt
val2_in_cent) return true else

return false class Item private int
lotno private String bidder private Money bid
107
Operator Overload
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 resnew Rational()
res.num r1.numr2.num res.den
r1.denr2.den return
res public void print() Console.WriteLine("
0/1",num,den)
109
public class Ex1 public static void Main()
Rational r1new Rational(2,3) Rational r2new
Rational(1,2) Rational res1Rational.mult(r1,r2
) Console.Write("Result of mult ")
res1.print() double res2Rational.translate(r
2) Console.Write("Result of
Translation0",res2) Console.Read()
110
(No Transcript)
111
Now we will rewrite using Operator Overload
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 resnew
Rational() res.num r1.numr2.num
res.den r1.denr2.den return res public
void print() Console.WriteLine("0/1",num,de
n)
113
public class Ex1 public static void Main()
Rational r1new Rational(2,3) Rational r2new
Rational(1,2) Rational res1r1 r2
Console.Write("Result of mult ")
res1.print() double res2(double) r2
Console.Write("Result of Translation0",res2)
Console.Read()
114
Now to handle printing
Rational res1r1 r2
Console.Write("Result of mult ")
res1.print()
115
class Rational private int num, den
public static implicit operator float (Rational
r1) return
(float) r1.num/r1.den
116
public class Ex1 public static void
Main() Rational r1new Rational(2,3)
Rational r2new Rational(1,2) Rational res1r1
r2 Console.Write("Result of mult 0",
res1)
117
Q710. CompleX Numbers
Create a complex number class with real and
imaginery Parts. Include opeartor overload for
and Plus implicit and implicit casting
118
Section 8 - UML Static Modelling
Section 8.1 Class Diagrams
119
The Class Diagram
Classname attribute datatype operation(args
type) type
Classname
OR
120
The Class Diagram
Book Details
Software Course
1 0..
0..
1..
Author
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
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
Example UML Class
Invoice amount Real date
DateCurrent_date customer String
specification String - administration
Stringunspecified - number_of_invoices
Integer status Statusunpaid paid, unpaid
Name, bold Public, typed Default
value Private Class variable property
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

125
Association
  • One player may be a member of many teams
  • (United Ireland)
  • Player may leave one team join another




Team
Player
126
Associations Cardinality
Association Name
Class1
Class1
  • Exactly One (default)
  • Zero or more
  • Optional (zero or one)
  • One or more
  • Numerically specified

Class

Class
0..1
Class
1..
Class
3..8
Class
127
Cardinality Examples
Employee NameString NumberInteger
Association Name


Dept NameString
0..1 Rent

Video
Member
Car Reg String year Integer
Hires
Customer
128
Class Object Representation


0..1 Rent

Video
Member
TsmithMember
Rocky Video
SpaceBalls Video
129
Association example
Insurance Policy
0..1 is
expressed in 1

expresses an
1 owns 0..
Insurance company
Insurance Contract
refers to
0..1
refers to
1..

has
Note Insurance Policy sent after
contract agreed
Customer
130
Association example expanded
Insurance Policy
0..1 is
expressed in 1

expresses an
Insurance company
1 owns 0..
Insurance Contract
refers to
insurer
0..1
refers to
1..

has
Person
wife
husband
Married to
131
Aggregation Composition
  • Special type of association
  • consists of
  • contains
  • part of


132
0..1
Delivery_Van regString
Employee
Contract
Aggregation
133
Owner nameString
Car
Service_record
Aggregation
134
TextField

JFrame

Listbox

Button

MenuItem
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
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
Static Modelling 8.2
Section 8.2
Inheritance
138
Example
Car
General
Specific
Estate
Coupe
Hatchback
Saloon
139
Java Implementation
Account amtReal deposit()
ATMAccount -pinInteger withdraw()
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
Concrete Subclasses
Car abstract
Estate
Coupe
Hatchback
Saloon
142
Polymorphism
Shape colourColour Draw()abstract
Square Draw()
Circle Draw()
143
Ways of showing constraints
Class A
Class A
constraint 1, constraint2
constraint 1, constraint2
Class C
Class D
Class B
Class C
Class D
Class B
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
Overlapping Inheritance
Vehicle
overlapping
Boat
Car
Hovercraft
146
Complete Inheritance
Person
complete
Woman
Man
  • No further class may inherit from Person in
    future

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 dont use a computer at
all. The company has 2 types of computer IBM
and Apple. Some of the IBMs have Multimedia
capability.
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 banks 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
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
Appendix 1- Chapter 7 Aggregation Association
151
Aggregation
class Height private int feet,
inches public Height( int f, int i )
feetf inches I public Height( )
feet 0 inchesi public Height(
Height h ) feet h.feet inches h.inches
public int height_in_inches()
return (inches feet12) public
void print() System.out.print(feet-inches\
)
152
class Student private int age private
String name private Height ht public
Student( int a, String n, int f, int i )
htnew Height(f,i)
agea namen public int
read_height_in_inches() return
ht.height_in_inches() public void
print()
System.out.print(Ageage \nName name
System.out.print(\nHei
ght) ht.print()

153
public class Test public static void
main(String args) Student
s1new Student(20, J.Smith, 5,11)
int result s1.read_height_in_inches()
System.out.println(Height in
insresult) s1.print()
154
Association
class Height private int feet,
inches public Height( int f, int i )
feetf inches I public Height( )
feet 0 inchesi public Height(
Height h ) feet h.feet inches h.inches
public int height_in_inches()
return (inches feet12) public
void print() System.out.print(feet-inches\
)
155
class Student private int age private
String name private Height ht public
Student( int a, String n, Height h )
agea namen hth public
int read_height_in_inches() return
ht.height_in_inches() public void
print()
System.out.print(Ageage \nName name
System.out.print(\nHei
ght) ht.print()

156
public class Test public static void
main(String args) Height h1new
Height(5,11) Student s1new
Student(20, J.Smith, h1) int
result s1.read_height_in_inches()
System.out.println(Height in
insresult) s1.print()
157
See Appendix 1 - Additional Examples
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
158
class Rat
// Version 1 -Normal Inheritance
protected int num, den public Rat(int n,
int d)numn dend public int readnum()
return num public void print()
System.out.println("Rat "num"/"den) clas
s RatSign extends Rat private char
sign RatSign(char s, int n, int d)
super(n,d) signs public int
readden()return den public void
print()System.out.println(signnum"/"den)

159
public class Version1 public static void
main(String args) Rat rArray new
Rat2 Rat r new Rat(2,3)
RatSign rs new RatSign('-', 3, 4)
rArray0 r rArray1 rs for( int i
0 i lt rArray.length i )
rArrayi.print()
160
abstract class Rat
// Version 2 Abstract function
protected int num, den public Rat(int n,
int d)numn dend 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) signs public int
readden()return den public void
print()System.out.println(signnum"/"den)

161
public class Version2 public static void
main(String args) Rat rArray new
Rat2 // Rat r new Rat(2,3) -
not allowed RatSign rs2 new
RatSign('',2,3) RatSign rs new
RatSign('-', 3, 4) rArray0 rs2
rArray1 rs for( int i 0 i lt
rArray.length i )
rArrayi.print()
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)
numn dend signs public int
readnum()return num public int
readden()return den public void
print()System.out.println(signnum"/"den)

163
public class Version3 public static void
main(String args) Rat rArray new
Rat2 RatSign rs2 new
RatSign('',2,3) RatSign rs new
RatSign('-', 3, 4) rArray0 rs2
rArray1 rs for( int i 0 i lt
rArray.length i )
rArrayi.print()
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) numn dend signs
public int readnum()return num public int
readden()return den public void
print()System.out.println(signnum"/"den)

165
public class Version4 public static void
main(String args) Rat rArray new
Rat2 RatSign rs2 new
RatSign('',2,3) RatSign rs new
RatSign('-', 3, 4) rArray0 rs2
rArray1 rs for( int i 0 i lt
rArray.length i )
rArrayi.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
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 Value2
    values0new Intvalue() values1new
    Floatvalue() ) for( int i 0 i lt
    values.length i )
    valuesi.setValue(i2)
  • valuesi.printValue()
Write a Comment
User Comments (0)
About PowerShow.com