Object oriented programming (OOP) explained with an
example
Create a class that keeps track of a bank account balance. Then write a program to use this
class.
Steps involved:
• Run the class builder utility (SE24).
• Create a class called ZKL_ACCOUNT
• Declare a PRIVATE attribute BALANCE of type DMBTR to store the account
balance.
• Create the following PUBLIC methods:
o SET_BALANCE (Sets the balance to a new value)
IMPORTING NEW_BALANCE TYPE DMBTR
o DEPOSIT (Adds a deposit amount to the balance and returns the new
balance)
IMPORTING AMOUNT TYPE DMBTR
RETURNING NEW_BALANCE TYPE DMBTR
o WITHDRAW (Subtracts a deposit amount from the balance and returns
the new balance.)
IMPORTING AMOUNT TYPE DMBTR
RETURNING NEW_BALANCE TYPE DMBTR
EXCEPTIONS INSUFFICIENT_FUNDS
• Activate all elements of your class.
• Write a program called Z_ ACCOUNT_REP. This program should do the
following:
o Instantiate an instance of the Account class.
o Set the account balance to some initial value.
o Make several deposits and withdrawals, printing the new balance
each time. Do not allow the balance to become less than zero.
(Use the exception to detect this.)
• Test and debug your program.
Step-by-step approach with screen-shots
Go to SE24 (Class builder)
Type in ZKL_ACCOUNT as the name of the class and press Create.
Kalyan [email protected]
Define 3 methods DEPOSIT, SET_BALANCE and WITHDRAW.
Place the mouse cursor in DEPOSIT and hit the Parameters button.
Write the parameters imported / exported for DEPOSIT method.
Similarly for SET_BALANCE
And WITHDRAW
Kalyan [email protected]
For withdraw we define an exception.
Now we IMPLEMENT the 3 methods. Double click the method DEPOSIT.
Write the required code. Similarly for SET_BALANCE
Similarly for WITHDRAW.
Kalyan [email protected]
Now we are almost done creating the object. Press CTRL + F3 to activate or hit the Matchstick.
We will see this in the status
Now we are done building the global class we can test it. Press F8.
Click SET_BALANCE. Write the NEW_BALANCE and press ENTER.
Kalyan [email protected]
We come back to Initial Screen. Now click DEPOSIT.
We see the return Values now.
Now let’s WITHDRAW 4000
Now the BALANCE is 2000
Lets try withdrawing 3000 now.
Kalyan [email protected]
We get an exception.
Given below is an example code for using the global class we defined.
REPORT ZGB_OOPS_BANK .
DATA: acct1 type ref to zaccountaa.
DATA: bal type i.
create object: acct1.
selection-screen begin of block a.
parameters: p_amnt type dmbtr,
p_dpst type dmbtr,
p_wdrw type dmbtr.
selection-screen end of block a.
start-of-selection.
call method acct1->set_balance( p_amnt ).
write:/ 'Set balance to ', p_amnt.
bal = acct1->deposit( p_dpst ).
write:/ 'Deposited ', p_dpst ,' bucks making balance to ', bal.
bal = acct1->withdraw( p_wdrw ).
write:/ 'Withdrew ', p_wdrw ,' bucks making balance to ', bal.
This is the output.
Kalyan [email protected]
Kalyan [email protected]