Presentation on theme: "1 FIT1002 Computer Programming Lecture 3: Introduction to Object-Orientation."— Presentation transcript:
1 FIT1002 Computer Programming Lecture 3: Introduction to Object-Orientation
2 Topics Problem Decomposition Objects = State + Behaviour Classes Inheritance Classes versus Instances Reading: The Java Tutorial, Chapter 2 (3rd Ed)
3 Object-oriented Programming Java is an object-oriented (OO) programming language OO languages center the description/coding of algorithms around the description of objects that are handled in the algorithm OO languages are a relatively recent development, other languages use other abstraction mechanisms Object-oriented programs are generally easier to maintain
4 Components of an Algorithm Values and Variables Instruction (a.k.a. primitive) Sequence (of instructions) Selection (between instructions) Repetition (of instructions) Abstractions (with Objects and Methods) => Object-orientation (next week) Documentation (beside instructions)
5 Object-oriented Modelling To model a problem it appears “natural” to start by modelling the objects that are concerned Objects have attributes and can behaviours Attributes and Behaviours are determined by the “type” of the object. Problem State “Attributes” Behaviour “Methods” Objects
6 Attributes and Behaviour Car Cat AttributesBehaviour Registration number Make Model Year Colour Start Stop Turn Accelerate Name Breed Colour Age Weight Registration number Sleep Eat Purr Climb Scratch
7 Example: Othello which kind of objects and behaviours would you model? (Granularity is determined by the problem)
8 Classes are Object Schemata We often describe the classes in a problem and their relationships in class diagrams. A Class Diagram gives a class name, the attributes and the behaviours. Game Stone color: “black/white” used: “yes/no” position: (x/y) with x,y = set remove turnOver Name Attributes Behaviours Later we will make precise how to specify admissible attribute values
9 Classes versus Instances A class describes a type of object and gives a general schema for all objects of this type –eg: “Car Manufacturer” An instance is a concrete object and belongs to a certain class –eg: “Holden”, “Toyota”, “Honda”,... To work with an object we must create an instance of the class and give its attributes appropriate values.
10 State of an Object The state of an object is usually captured with the values of its attributes Game Stone #1 color: “black” used: “yes” position: (4/5) Game Stone #2 color: “white” used: “yes” position: (4/4) The values of attributes can change during the lifetime of the object (usually through invocation of a behaviour)
11 Object Identity Problem: Is an object fully identified by its attribute values? What if we have two stones with the same colour on the same field? Game Stone #1 color: “black” used: “yes” position: (4/4) Game Stone #2 color: “black” used: “yes” position: (4/4) Objects have a unique identity and are distinguishable! (“Game Stone # 2)
12 The Person Class Person name age display getAge getName setAge setName Name of class Attributes of an object instantiated from this class Behaviour of an object instantiated from this class
13 Information Hiding name age Normally, attributes of objects should not be directly accessed. The purpose of this is “safer” program design.
14 Get/Set Methods Instead we define a behaviour that “tells us” the attribute value when requested. Similarly, we will define behaviours to set and change attribute values. name age getName "Jack"
15 Interfaces The set of all behaviour that can be invoked on an object is its public interface. The rest of the program can only access an object through its interface. An interface can also contain publicly visible attributes (but it normally shouldn’t) display getAge getName setName setAge
16 Sending a Message to an Object There are 3 parts in a message sent to an object: the name of the object that is the receiver the action that the receiver is requested to take in parentheses, any extra information the receiver needs to know. In Java, the syntax for asking a Person instance called bestFriend to tell you its name would be: bestFriend.getAge()
17 Passing Information in a Message When an object needs to know some extra information in order to do what you want, you can pass it that information with the message. Let us assume the Person class also has an Address attribute. If your bestFriend moves house and you want to update the object’s adress attribute, you need to send it a message that tells it to change the address, and also what to change it to. The extra information is called arguments or parameters. bestFriend.setAddress(“17 Grosvenor St.”)
18 Designing a Solution to a Problem The problem: write a program that simulates a bank. The bank has a collection of accounts. To simpify it, we will assume that each account has an account type (e.g. savings or cheque), a client who owns the account, and a current balance.
19 Some Scenarios 1. A client wants to open a new account. 2.A client wants to close an account. It happens successfully. The account number is not one that the bank knows about. 3. A client wants to deposit an amount of money into a particular account. It happens successfully. The account number is not one that the bank knows about. The amount of money is negative.
20 More Scenarios 4. A client wants to withdraw an amount of money from a particular account. It happens successfully. The account number is invalid. The amount of money is negative. The amount is more than the current balance. 5. ….
21 What Does the Bank Need to Be Able to Do? Create a new account and get the details Close an existing account Deposit money into an account –Check that the account exists –Check that the amount is reasonable Withdraw money from an account –Check that the account exists –Check that the amount is reasonable –Check that the amount does not exceed the current balance
22 What Does the Bank Need to Know? The bank needs to know which account(s) it has. Each account has an account number as a unique identifier.
23 The Bank Class Bank closeAccount deposit display openAccount withdraw accounts numberOfAccounts nextAccountNumber
24 What Does an Account Need to Be Able to Do? Increase its current balance with a deposit. Decrease its current balance with a withdrawal. Show its current state. Return the values of all of its attributes. Change the values of all of its attributes except the account number. Set-up/initialize itself (read data from the keyboard). Validate any values that can be validated.
25 What Does an Account Need to Know? Its account number. The account type (savings, cheque, credit card, etc.). The owner of the account (the client). The current balance. Different types of accounts may need more information, e.g. a PIN, an overdraft limit. For now, we will assume that these are not relevant to our problem.
26 The Account Class Account accountNumber accountType owner balance deposit getAccountNumber inputDetails validAccountNumber withdraw
27 What Does a Client Need to Be Able to Do? Show its details. Change its details. Set its details (read data from the keyboard).
28 What Does a Client Need to Know? Its contact details (say name, address and phone number). Its bank account number.
29 The Client Class Client name address phoneNumber accountNumber getAddress getName inputDetails setAddress setName …
30 Aggregation Relationship There are several different kinds of relationships between the classes. In the Banking system, we have seen an aggregation relationship. The Bank has a set of Account s, and each account has a Client. The Bank consists of a set of Accounts and behaviours to act upon them. A "has a" relationship is an aggregation relationship. BlueJ shows these as dotted lines between the classes.
31 Class Diagram with Aggregation
32 Association Relationship In some programs, a class uses services provided by another class, but the other class is not a component of it. For example, the Banking system requires an Account object to input details from the keyboard. The Account asks the Client object to input some of those details. In order to do that, they both use a class called Scanner which is provided by Java. Neither Account nor Client "has a" KeyBoardReader, but they both use this class. This is a "uses" relationship.
33 Class Diagram with Association
34 Inheritance Relationship In the banking system, an Account had an attribute that specified its type (e.g. savings, credit card, cheque). In reality, each of these account types would have to be slightly different (e.g. a credit card account would have a credit limit, a PIN, etc.), but they would have many attributes and behaviours in common. This is an "is a" relationship. A ChequeAccount is an Account, a CreditCardAccount is an Account. We use inheritance in this circumstance. A ChequeAccount is a specialization (also subclass, subtype) of an account. We say the definition of a ChequeAccount “extends” the definition of Account. ChequeAccount “inherits” the definition of Account ( but it can modify and extend this).
35 Subclasses We use inheritance in order to remove duplication, and to use abstraction more effectively. (“Factoring”) We could have a generic Account class that has subclasses of SavingsAccount, ChequeAccount, CreditCardAccount, etc. In this example, Account would be the superclass. It would have the attributes and behaviours common to all accounts (e.g account number, owner details, deposit, withdraw). Each subclass would add attributes and behaviours specific to it (e.g. PIN, check credit limit). It can also override methods in the superclass (e.g. the withdraw behaviour in a credit card account would be different from a savings account). A subclass has all the attributes and behaviours of its superclass, and also its own particular ones.
36 Class Diagram with Inheritance
37 Multiple Inheritance In some situations, we might like a class to inherit from more than one other class. For example, we may have a Boat class and a Plane class. Boat would have behaviours such as float and reverse. Plane would have behaviours such as land and take off. They would have some behaviours in common, e.g. goForward. That might be in a superclass called Vehicle. A seaplane is a Plane, and it is also a Boat. It could inherit from both, so that it could do all of these things. Some programming languages allow for multiple inheritance. Java does not. This is due to the complications involved in resolving potential conflicts in multiple inheritance.
38 Summary An object-oriented programming language uses objects and classes. A class is a description of what an object would look like if one existed. A class is instantiated to create an object. An object has attributes and behaviours, identity and state. Scenarios are imaginary sequences of operations to achieve a result in a system. They are used to design classes and also to test them. Real systems involve interacting classes. Classes may have association, aggregation or inheritance relationships.