Implementing Classes Learning objectives By the end of this lecture you should be able to: design classes using the notation of the Unified Modeling Language.

Slides:



Advertisements
Similar presentations
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Advertisements

Classes and objects Learning objectives By the end of this lecture you should be able to: explain the meaning of the term object-oriented; explain the.
MSc IT Programming Methodology (2). number name number.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?
SD1042 Introduction to Software Development. Extending classes with inheritance Robot DancingRobot Sharing attributes and methods.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Our BankAccount class should define three methods  deposit  withdraw  getBalance How a programmer will carry out these operations?  We assume that.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
1 Classes and Objects Overview l Classes and Objects l Constructors l Implicit Constructors l Overloading methods this keyword l public, private and protected.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
MSc IT Programming Methodology (2). MODULE TEAM Dr Aaron Kans Dr Sin Wee Lee.
CS1020 Data Structures and Algorithms I Lecture Note #6 Exceptions Handling exceptional events.
Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: explain the term inheritance; design inheritance.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
CMP-MX21: Lecture 6 Objects & Methods 1 Steve Hordley.
Java Programming Week 6: Array and ArrayList Chapter 7.
Programming Methodology (1). import java.util.*; public class FindCost3 { public static void main(String[] args ) { Scanner sc = new Scanner(System.in);
Introduction to Object-Oriented Programming
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Teach.NET Workshop Series Track 4: AP Computer Science with.NET and J#
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
MSc IT Programming Methodology (2). Oblong EasyScanner BankAccount.
Object-Oriented Programming in C++
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
Introduction to Programming G50PRO University of Nottingham Unit 8 : Methods 2 - Arrays Paul Tennent
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Introduction to Java Java Translation Program Structure
Ch 23 Java in context Learning objectives By the end of this lecture you should be able to:  explain the difference between a reference and a pointer;
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
Fall 2006Slides adapted from Java Concepts companion slides1 Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter.
1 CSC 201: Computer Programming I Lecture 2 B. S. Afolabi.
Savitch - Chapter 11CS Extending the Class Capabilities Let’s extend the definition of the BankAccount class to illustrate some additional capabilities.
CSC1401 Strings (text). Learning Goals Working with Strings as a data type (a class) Input and output of Strings String operations.
ACM/JETT Workshop - August 4-5, : Defining Classes in Java.
Encapsulation ◦ Blackbox concept Data and method(s) Hidden details InterfaceEffect(s) methods called class.
Problem 1 Bank.  Manage customers’ bank account using the following operations: Create a new account given a customer’s name and initial account. Deposit.
Classes CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 3: An Introduction to Classes 1 Chapter 3 An Introduction to Classes.
WAP to find out the number is prime or not Import java.util.*; Class Prime { public static void main(string args[]) { int n,I,res; boolean flag=true;
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Lecture 3 John Woodward.
Data Structures and Algorithms revision
Java OOP Overview Classes and Objects, Members and Class Definition, Access Modifier, Encapsulation Java OOP Overview SoftUni Team Technical Trainers.
Chapter 2 Elementary Programming
Implementing Classes Yonglei Tao.
suggested reading: Java Ch. 6
CLASS DEFINITION (> 1 CONSTRUCTOR)
Chapter Three - Implementing Classes
You can work in groups on this program.
Lecture 2: Implementing ArrayIntList reading:
null, true, and false are also reserved.
Building Java Programs
Building Java Programs
د.سناء الصايغ الفصل الأول البرمجة الشيئية
Lecture 2: Implementing ArrayIntList reading:
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
Lecture Notes – Week 2 Lecture-2
JAVA CLASSES.
Introduction to Object-Oriented Programming
Presentation transcript:

Implementing Classes Learning objectives By the end of this lecture you should be able to: design classes using the notation of the Unified Modeling Language (UML); write the Java code for a specified class; explain the difference between public and private access to attributes and methods; explain the use of the static keyword; pass objects as parameters; implement collection classes based on arrays.

Implementing classes in Java A class consists of: a set of attributes (the data); a set of methods Oblong length height : double : double setLength setHeight getLength getHeight calculateArea calculatePerimeter Oblong () : double (double) (double) () () () : double : double : double (double, double)

The notation of the Unified Modeling Language (UML) Oblong length : double height : double Oblong(double, double) setLength(double) setHeight(double) getLength() : double getHeight() : double calculateArea() : double calculatePerimeter() : double

public class Oblong { double length; double height; private private public Oblong(double lengthIn, double heightIn) { } // more methods here } length = lengthIn; height = heightIn;

getLength() { } publicdouble return length; getHeight() { } publicdouble return height;

setLength() { } publicvoid length = lengthIn; double lengthIn setHeight() { } publicvoid height = heightIn; double heightIn

calculateArea() { } publicdouble return length * height; calculatePerimeter() { } publicdouble return 2 * (length + height);

The BankAccount class BankAccount accountNumber : String accountName : String balance : double BankAccount (String, String) getAccountNumber() : String getAccountName() : String getBalance() : double deposit(double) withdraw(double)

public class BankAccount { private String accountNumber; private String accountName; private double balance; public BankAccount(String numberIn, String nameIn) { accountNumber = numberIn; accountName = nameIn; balance = 0; }

public String getAccountName() { return accountName; } public String getAccountNumber() { return accountNumber; } public double getBalance() { return balance; }

public void deposit(double amountIn) { balance = balance + amountIn; } public void withdraw(double amountIn) { balance = balance – amountIn; } }

public class BankAccountTester { public static void main(String[ ] args) { BankAccount account1 = new BankAccount(" ","Susan Richards"); account1.deposit(1000); System.out.println("Account number: " + account1.getAccountNumber()); System.out.println("Account name: " + account1.getAccountName()); System.out.println("Current balance: " + account1.getBalance()); }

Amending the BankAccount class “ ” “Funmi Odulopo” £ “ ” “Mary Stephenson” £ “ ” “Dilraj Mann” £ acc1 acc2 acc3 1.25% 1.25% 1.25% acc1.getBalance(); acc1.getInterestRate(); acc2.addInterest (); acc2.getInterestRate(); acc3.deposit( 500 ); acc3.setInterestRate(1.5); Bank.setInterestRate(1.4); Bank.getInterestRate();

The static keyword private static double interestRate; public static void setInterestRate(double rateIn) { interestRate = rateIn; } public static double getInterestRate() { return interestRate; }

The addInterest method public void addInterest() { balance = balance + (balance * interestRate)/100; }

public class BankAccountTester2 { public static void main(String[] args) { BankAccount2 account1 = new BankAccount2(" ","Varinder Singh"); BankAccount2 account2 = new BankAccount2(" ","Lenny Roberts"); account1.deposit(1000); account2.deposit(2000); BankAccount2.setInterestRate(10); account1.addInterest();

System.out.println("Account number: " + account1.getAccountNumber()); System.out.println("Account name: " + account1.getAccountName()); System.out.println("Interest Rate " + BankAccount2.getInterestRate()); System.out.println("Current balance: " + account1.getBalance()); System.out.println(); System.out.println("Account number: " + account2.getAccountNumber()); System.out.println("Account name: " + account2.getAccountName()); System.out.println("Interest Rate " + BankAccount2.getInterestRate()); System.out.println("Current balance: " + account2.getBalance()); } }

Account number: Account name: Varinder Singh Interest rate: 10.0 Current balance: Account number: Account name: Lenny Roberts Interest rate: 10.0 Current balance:

Initializing attributes Java does not give an initial value to local variables but does initialize attributes; int double char Objects 0 boolean false null private static double interestRate = 0;

import java.util.*; public class EasyScanner { public static int nextInt() { Scanner sc = new Scanner(System.in); int i = sc.nextInt(); return i; } // more methods here }

public static double nextDouble() { Scanner sc = new Scanner(System.in); double d = sc.nextDouble(); return d; } public static String nextString() { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); return s; }

public static char nextChar() { Scanner sc = new Scanner(System.in); char c = sc.next().charAt(0); return c; }

public class ParameterTest { public static void main(String[] args) { BankAccount acc = new BankAccount("1", "Samsun Okoyo"); test(acc); System.out.println("Account Number: " + acc.getAccountNumber()); System.out.println("Account Name: " + acc.getAccountName()); System.out.println("Balance: " + acc.getBalance()); } private static void test(BankAccount accIn) { accIn.deposit(2500); } }

Account Number: 1 Account Name: Samsun Okoyo Balance:

Effect on computer memory public static void main (String[] args) { BankAccount acc = new BankAccount(….) ; } Computer MemoryJava Instructions acc a BankAccount object private static void test(BankAccount accIn) { } accIn test(acc); accIn.deposit(2500);

Collection classes When one object itself consists of other objects, this relationship is called aggregation; A collection class is an implementation of the aggregation relationship. BankAccount Bank *

Bank list: BankAccount [ ] total : int Bank(int) search(String) : int getTotal() : int isEmpty() : boolean isFull() : boolean add(BankAccount) : boolean getItem(String) : BankAccount depositMoney(String, double) : boolean withdrawMoney(String, double) : boolean remove(String) : boolean

public class Bank { private BankAccount[] list; private int total; public Bank(int sizeIn) { list = new BankAccount[sizeIn]; total = 0; }

private int search(String accountNumberIn) { for(int i = 0; i ; i++) { } return -999; } BankAccount tempAccount = list[i]; String tempNumber = tempAccount.getAccountNumber(); if(tempNumber.equals(accountNumberIn)) { return i; } < total

public int getTotal() { return total; } public boolean isEmpty() { if (total == 0) { return true; } else { return false; } }

public boolean isFull() { if (total == list.length) { return true; } else { return false; } }

public boolean add(BankAccount accountIn) { if( ) { return true; } else { return false; } } (!isFull() list[total] = accountIn; total++;

public BankAccount getItem(String accountNumberIn) { int index; index = search(accountNumberIn); if(index == -999) { return null; } else { return list[index]; } }

public boolean depositMoney (String accountNumberIn, double amountIn) { int index = search(accountNumberIn); if(index == -999) { return false; } else { list[index].deposit(amountIn); return true; } }

public boolean remove(String numberIn) { int index = search(numberIn); if(index == -999) { return false; } else { // remove item from list return true; } }

4th item 3rd item 2nd item 1 st item Item to delete 5th item Smith Adams Patel Okoya Ling Patel Adams Smith list list[index] = list[index+1]; list[index+1] = list[index+2]; list[index+2] = list[index+3]; total--; list[i] = list[i+1]; for(int i = index; i<= total-2; i++) { }

public class BankProgram { public static void main(String[] args) { char choice; int size; System.out.print("Maximum number of accounts? "); size = EasyScanner.nextInt(); Bank myBank = new Bank(size);

do { System.out.println(); System.out.println("1. Create new account"); System.out.println("2. Remove an account"); System.out.println("3. Deposit money"); System.out.println("4. Withdraw money"); System.out.println("5. Check account details"); System.out.println("6. Quit"); System.out.println(); System.out.print("Enter choice [1-6]: "); choice = EasyScanner.nextChar(); System.out.println();

switch (choice) { case '1': option1(myBank); break; case '2': option2(myBank); break; case '3': option3(myBank); break; case '4': option4(myBank); break; case '5': option5(myBank); break; case '6': break; default: System.out.println("Invalid entry"); } }while (choice != '6'); }

// add account private static void option1(Bank bankIn) { System.out.print("Enter account number: "); String number = EasyScanner.nextString(); System.out.print("Enter account name: "); BankAccount account = new BankAccount(number, name); boolean ok = bankIn.add(account); if (!ok) { System.out.println("The list is full"); } else { System.out.println("Account created"); } }

// remove account private static void option2(Bank bankIn) { System.out.print("Enter account number: "); String number = EasyScanner.nextString(); boolean ok = bankIn.remove(number); if (!ok) { System.out.println("No such account number"); } else { System.out.println("Account removed"); } }

// deposit money private static void option3(Bank bankIn) { System.out.print("Enter account number: "); String number = EasyScanner.nextString(); System.out.print("Enter amount to deposit: "); double amount = EasyScanner.nextDouble(); boolean ok = bankIn.depositMoney(number, amount); if (!ok) { System.out.println("No such account number"); } else { System.out.println("Money deposited"); } }

// withdraw money from an account private static void option4(Bank bankIn) { System.out.print("Enter account number: "); String number = EasyScanner.nextString(); System.out.print("Enter amount to withdraw: "); double amount = EasyScanner.nextDouble(); boolean ok = bankIn.withdrawMoney(number, amount); if (!ok) { System.out.println("No such account number"); } else { System.out.println("Money withdrawn"); } }

// check account details private static void option5(Bank bankIn) { System.out.print("Enter account number "); String number = EasyScanner.nextString(); BankAccount account = bankIn.getItem(number); if (account == null) { System.out.println("No such account number"); } else { System.out.println("Account number: " + account.getAccountNumber()); System.out.println("Account name: " + account.getAccountName()); System.out.println("Balance: " + account.getBalance()); System.out.println(); } }

Maximum number of accounts? Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: 1

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: Enter account name: Account created Paula Wilkins 1

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: Enter account name: Account created Sydney Isaacs 1

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: Enter account name: Account created Delroy Joseph 3

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: Enter amount to deposit: Money deposited

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: Account removed

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: No such account number

1. Create new account 2. Remove an account 3. Deposit money 4. Withdraw money 5. Check account details 6. Quit Enter choice [1-6]: Enter account number: Account number: Account name: Delroy Joseph Balance: