CMPMX 21 Lecture 6 Objects Methods 1 Steve

CMP-MX 21: Lecture 6 Objects & Methods 1 Steve Hordley

Overview So far we have seen the basics of JAVA: we know most of the words which make up the language and have seen some simple programs In the remainder of the course we will look at how we design and construct more complex programs in JAVA is an object oriented programming (OOP) language. To use it properly we need to understand what this means

What is an object? In the real world we encounter objects all around us: ourselves, cats, dogs, cars, and houses etc. are all objects All objects can be characterised by their state and their behaviour An object’s state describes its attributes. For example a dog has a certain breed and colour and it can be hungry, thirsty or tired etc. An object’s behaviour describes what it does. For example a dog can be barking, sitting, running or eating etc.

What is an object? An object does not need to be something physical. It might be a bank account or a song or something even more abstract like a mathematical theory In JAVA and OOP in general an object is simply a model of some real world object. When designing an object oriented program we begin by determining which objects we need to model

An Example Suppose we want to write a program to look after a bank’s customer accounts. We will need to keep track of the banks customers and their accounts. We will need to be able to keep up-to-date records of a customer’s personal information such as their address and to record and track any transactions which occur on their account.

An example Given a rough program specification of this form the first step is to extract potential objects which we need to model. Address Transactions Customer Bank Account Personal Information

An example Once we have extracted all the objects we need to model we next need to think about the following questions: What attributes of the objects do we need to model? How will the different objects interact with one another? What actions or behaviours do each of the objects have? Note: this process is likely to be an iterative one: the actions we need to implement will affect what attributes of an object we will model and visa versa

Object Oriented Programming Good modelling of objects and their interactions/behaviours is the key to making our code re-usable: A good model makes it easy to extend our programs to perform new tasks Once all the objects are modelled we must convert the model to JAVA code Once this code is written we can use it to perform the required tasks.

Object Oriented JAVA Key to modelling objects in JAVA is the concept of a class We can think of a class as a blueprint for an object: it tells us how to make a particular object. Two types of information are contained in a class: the attributes (or states) that an object has and the behaviours (or actions) it has Attributes are represented using variables while behaviours are implemented with methods (we will discuss methods later).

An example Continuing with our example, let us begin by designing a simple class to represent a bank account. A simple bank account might be modelled thus: Class: bank account Account number Account holder These are the class attributes or states. Account balance Make Deposit Make Withdrawal Calculate Interest These are the behaviours or actions which are associated with the bank account

Coding the class in JAVA class bank. Account { // Class variables (data) private String account. Name; private String account. Holder; private float account. Balance; // Class actions (methods) … }

Coding the class in JAVA class bank. Account {. . . } A class definition begins with the class keyword and is contained between curly brackets {} Class attributes (data) are represented as variables which are declared in the same way as we have seen variable declarations previously: private String account. Name; private String account. Holder; private float account. Balance;

The private keyword Note that the variable declaration here is modified with the private keyword: private String account. Name; Declaring a variable private means that it cannot be changed by code which is not in the class definition in which the variable is declared. Keeping variables private to a class makes more work for the person who designs the class: we need to write code to change variables

The private keyword Often changing a variable is not a simple matter: we might have to perform a series of checks to ensure that the variable is changed to a valid value By forcing the change to be coded in the class definition we ensure that whenever the class is used, variables are changed in a valid way This approach also has the advantage that the code to change (and check validity of) a variable only needs to be written once. It can then be called (used) many times with no further programming effort

The public keyword In our programs so far we are used to seeing variable declarations of the form: String account. Name; This declares a public variable rather than a private one. We can make this explicit by writing: public String account. Name; If neither modifier public or private is included the variable defaults to public

The public keyword A public variable can be modified outside of the class in which it is defined When designing and implementing classes we should make all our variables private unless we can think of a good reason to make them public There is a third modifier called protected which is somewhere between private and public. We will not discuss the function of this keyword in this course.

Classes versus objects So far we have only a class: a blueprint of an object. We use the class definition to create actual instances (objects) of the given class: Object 1 13456302 D. J. Smith 350. 23 Class: bank Account number Object 2 Account holder 63817845 Account balance R. G. Hunt Make Deposit 5034. 62 Make Withdrawal Calculate Interest Object 3 49714294 W. H. Freeman 534. 60

Creating objects from classes We can define a particular instance of a class in a program with the following piece of code: // Creating a bank account object class my. Program { public static void main( String [] args ) { bank. Account my. Bank. Acct; my. Bank. Acct = new bank. Account(); } Class name Object name Call to the class constructor method

Creating objects from classes bank. Account my. Bank. Acct; The first line is just a variable declaration. It declares a reference variable of type bank. Account which is called my. Bank. Acct Remember a reference variable holds an address: it tells us where to find the object of type bank. Account. After this line my. Bank. Acct holds the address null: we haven’t yet actually created the object so it doesn’t have an address

Creating objects from classes It is the second line which actually creates the bank. Account object: mybank. Acct = new bank. Account(); The keyword new is used to create a new object. The new keyword reserves the memory for the object which is being created. The new keyword must be followed by a constructor method for the class of object which is being created. But what is a constructor method and what does it do?

A word about methods In JAVA a method is essentially a set of instructions which are given a particular name: my. Method() { statements; The method name followed by a set of parentheses denotes the start of a method. } The statements to be performed by the method are placed between curly brackets

A word about methods When we want to execute the statements in a method we call the method from our program: // A simple program class my. Program { public static void main( String [] args ) { my. Method(); } This line “calls” the method with name my. Method

A word about methods Our code to create a bank account object contains a call to a method: mybank. Acct = new bank. Account(); This method called bank. Account() has the same name as our class. It is a special method called a constructor method. Whenever we create a class, JAVA automatically creates an associated method: the constructor method. It’s job is to initialise the values of the object’s variables

The constructor function MEMORY (Created by new) MEMORY my. Bank. Acct (Created by the variable declaration) null Account number null Account holder 0. 0 Account balance The default constructor method which JAVA creates assigns all an object’s variables their default values

Creating multiple objects We can declare as many instances of a class (i. e. objects) in our programs as we require: // Creating a bank account object class my. Program { public static void main( String [] args ) { bank. Account my. Bank. Acct, another. Acct; my. Bank. Acct = new bank. Account(); another. Acct = new bank. Account(); } Each time we create (construct) an object, memory is set aside for it by the constructor function:

Creating multiple objects my. Bank. Acct another. Acct null Acct. no. null Acct. holder 0. 0 Acct. balance

Class variables Every time we create an object we create new instances of all the relevant variables: e. g. creating a bank account object creates an account number, an account name and a balance This makes sense because all these variables are particular to a given object: each bank account has a different number, and a potentially different holder and balance Sometimes however, objects will contain variables which are common to all variables in the class

Class variables For example, suppose we extend our bank account class to include an interest rate. We could extend our class definition to add an extra variable: class bank. Account { // Class variables (data) private String account. Name; private String account. Holder; private float account. Balance; private float interest. Rate; // Class actions (methods) } interest. Rate variable added here

Class variables Now, each time we create (construct) a bank account object JAVA reserves space for four variables: my. Bank. Acct null Acct. no. null Acct. holder 0. 0 Acct. balance 0. 0 Interest Rate But, the interest rate has a value which is common to all bank accounts. So it would be more efficient if we could somehow avoid keeping a copy of this variable with every object.

Class variables We achieve this in JAVA by defining interest. Rate to be a class variable: private static float interest. Rate; A class variable is created by modifying the variable declaration with the keyword static. Note: class variables are sometimes called static variables. However, this is a slightly confusing term since static variables are not fixed as the name suggests, rather they can change just as other variables.

Class variables A class variable is created when the JAVA interpreter loads the class in which it is defined. A class variable exists independently of any objects of the class. If our program has 10 bank. Account objects, there will still be only a single interest. Rate variable.

Using classes Whenever we define a class in JAVA we should save it in its own file and this file should have the same name as the class with the. java extension. So, our bank. Account class will be saved in a file called bank. Account. java To use the class in our programs we must first compile the class: C: myjavacode>javac bank. Account. java On successful compilation the JAVA compiler will produce a file called bank. Account. class

Using classes Next, we need to write the code that actually uses the bank. Account class. (For example the program we saw earlier which creates a bank. Account object). We then compile and run this program in the usual way: C: myjavacode>javac my. Program. java C: myjavacode>java my. Program Note: To use the bank. Account class JAVA needs to be able to find the bank. Account. class file. Putting it in the same directory as our program code ensures this.

Classes and programs Note: all the programs we have written so far have in fact been class definitions: // Creating a bank account object class my. Program { public static void main( String [] args ) { bank. Account my. Bank. Acct, another. Acct; my. Bank. Acct = new bank. Account(); } They all begin with the class keyword. In fact any program we write in JAVA is also a class definition.

Classes and programs The programs we have written up to now are special classes because they also contain the special method main. Remember, if we want to be able to execute (run) a program it must contain a main method. So, bank. Account. class is not executable because it doesn’t contain a main method. To use the methods in bank. Account. class we must call them from other classes.

A summary so far So far we have seen how to define a basic class and how to create an object of a particular class in a program At the moment our class definition is not very useful because we can’t do anything with it apart from create bank. Account objects. To make the class more useful we need to add methods to it which allow us to change the attributes of a bank. Account e. g. to change an account balance. To do this we need to understand a little bit more about methods.

More about methods We said earlier than a method is simply a named set of instructions which can be called in a program. For example, consider the following method which provides the balance on an account: // Get account balance public float get. Balance( ){ return account. Balance; }

More about methods The first line begins the definition of a new method called get. Balance: public float get. Balance( ) The method name: get. Balance must be followed by parentheses ( ) Here we have two keywords in front of the method name: public and double. These keywords modify (change) different aspects of the method’s behaviour They are similar to the modifiers we place in front of a variable declaration

The public keyword Placing the keyword public in front of a method name means that the method is visible (can be called) from outside the class definition So for example, we could write a program which creates bank. Account objects and then queries their balance using get. Balance(). Sometimes we will want to write methods which are only visible (can only be called) within a certain class. We call this hiding the method and we use the keyword private rather than public to define such a method.

The float keyword Placing the keyword float in front of the method name tells JAVA that the method will return a value of type float. A method can return a value of any type: e. g. int, boolean, double, or it can return a reference to an object of any defined class, e. g. String, bank. Account. Some methods don’t return any variable this is indicated using the void keyword: public void my. Method( )

The method statements Method statements follow the method name and are placed between curly brackets: public float get. Balance( ){ method statements go here; } The method get. Balance contains a single statement: return account. Balance;

The return keyword tells JAVA to stop executing the method statements and return to the point where the method was called from If the method returns a value the return keyword must be followed by a variable (or literal constant) of the relevant type return account. Balance; Here return is followed by the variable name account. Balance which has a type of float. This matches the return value of the method get. Balance().

Calling a method To use the get. Balance method we would write the following piece of code: class my. Program { public static void main( String [] args ) { float the. Balance; bank. Account my. Bank. Acct; my. Bank. Acct = new bank. Account(); the. Balance = my. Bank. Acct. get. Balance(); System. out. println(“The balance is ”+the. Balance); }

Calling a method The method is called using the dot operator. : my. Bank. Account. get. Balance() In English this statement means call the method get. Balance() for the object my. Bank. Account When JAVA reaches this statement it executes the method get. Balance(). This method simply returns the value of account. Balance for the relevant object. The relevant object is the object for which the method is called: my. Bank. Account in this case.

Calling a method Because get. Balance() returns a value, we can assign this value to a variable of the appropriate type: the. Balance = my. Bank. Acct. get. Balance(); the. Balance has a type of float so this assignment is valid Note: we can call the method without an assignment too: my. Bank. Acct. get. Balance(); In this case the returned value is lost and cannot be accessed.

Another method In addition to getting the balance on an account we will likely want to perform transactions. For example we might want to deposit an amount in the account. The following method takes care of this: // Make a deposit public void make. Deposit( float amount ){ if (amount >= 0 ) account. Balance += amount; else System. out. println(“Cannot deposit a negative amount”); }

The method definition public void make. Deposit( float amount ){ We want to be able to call this method from outside the class definition so we define it public. The method doesn’t need to return a value so we use the keyword void In this method definition we have included what looks like a variable declaration between the parentheses This variable declaration is called a method argument. Method allow us to pass data (variables) to the method from where we call the method

Calling a method with arguments When calling a method with arguments we must pass all the arguments which the method requires: class my. Program { public static void main( String [] args ) { float the. Balance; bank. Account my. Bank. Acct; my. Bank. Acct = new bank. Account(); my. Bank. Acct. make. Deposit(500. 63 f); the. Balance = my. Bank. Acct. get. Balance(); System. out. println(“The balance is ”+the. Balance); }

Calling a method with arguments my. Bank. Acct. make. Deposit(500. 63 f); We must ensure that the correct type is passed to the method. Here the f forces the value to be a floating point value We can also pass a variable: float the. Amount = 500. 63 f; my. Bank. Acct. make. Deposit(the. Amount);

Calling a method with arguments Note: when we pass a variable to a method it is the value of the variable which is passed not the actual value: float the. Amount = 500. 63 f; my. Bank. Acct. make. Deposit(the. Amount); 500. 63 the. Amount Main program calls the method make. Deposit public void make. Deposit(float amount) When make. Deposit is called, JAVA creates a new variable: amount and initialises its value to be the value of the. Amount 500. 63 amount

Calling a method with arguments Because arguments are passed in this way, the method cannot change the passed variable That is, the method make. Deposit cannot change the. Amount. So adding the following line to the method make. Deposit changes the variable amount not the variable the. Amount public void make. Deposit(float amount) amount +=10; . . .

Method arguments A method can have multiple arguments of different types: public void my. Method( int arg 1, double arg 2, boolean arg 3 ){ Method arguments can be reference variables to objects. For example I might write a method which takes a bank. Account object as an argument: public void my. Method( bank. Account a. Bank. Account ){ a. Bank. Account. make. Deposit(435. 34 f); }

Method arguments What happens when this method is called? : class my. Program { public static void main( String [] args ) { bank. Account my. Bank. Acct = new bank. Account(); my. Method( my. Bank. Acct ); the. Balance = my. Bank. Acct. get. Balance(); System. out. println(“The balance is ”+the. Balance); } C: myjavacode>java my. Program The balance is 435. 34

Method arguments In this case the call to my. Method which takes my. Bank. Account as an argument actually changes the value of account. Balance for the object my. Bank. Account my. Bank. Acct The method call copies the address to the variable a. Bank. Account null Acct. no. null Acct. holder 0. 0 Acct. balance Created by main program The variable a. Bank. Account is created by the method my. Method The address it contains refers to the location of the object created in the main program

Other methods Retrieving the account number for an account can be done with the following method: // Get account number public String get. Account. Number( ){ return Account. Number; } Similarly, retrieving the account holder: // Get account holder public String get. Account. Holder( ){ return Account. Holder; }

Other methods We might also want to be able to make a withdrawal: // Make a withdrawal public void make. Withdrawal( float amount ){ if (amount >= 0 ){ if (account. Balance-amount>=0) account. Balance -= amount; else System. out. println(“Can’t withdraw this much”); } else System. out. println(“Cannot deposit a negative amount”); }

Other methods We might also want to calculate the daily interest on an account balance: // Calculate daily interest public float get. Daily. Interest( ){ return account. Balance*interest. Rate/100/365; }

Other methods We might also want to change the interest rate for the class: // Change interest rate public static void change. Interest. Rate( float new. Rate ){ interest. Rate = new. Rate; } This method is a little different to the methods we have seen so far. The variable it is changing is a class variable not an object variable The method is particular to the class and independent of any particular class object

Class methods We call methods which change class variables class methods. A method is declared as a class method using the keyword static: public static void change. Interest. Rate( float new. Rate ) A class method cannot change none class variables. For example the following is an invalid method: public static void change. Balance( float new. Balance ){ balance = new. Balance; } balance is not a class variable

Calling class methods A class method should be called with the dot operator but using the class name rather than an object name: class my. Program { public static void main( String [] args ) { bank. Account my. Bank. Acct = new bank. Account(); bank. Account. change. Interest. Rate(4. 5 f); my. Bank. Acct. change. Interest. Rate(3. 1 f); } Using the name of any relevant class object will also work but should be avoided since the action is not applied to a particular object but the whole class

A summary This lecture has introduced the concept of an object: a programming model of a real world object. We have seen how to model objects in JAVA using the concept of a class We have seen that classes model an object’s attributes using variables and its actions or behaviours using methods We have looked at how to create an instance of a class (an object) from its class definition using a constructor method

A summary We have introduced the concept of methods in JAVA and have seen how to write simple methods when developing a class We have looked at how we can return values from methods and pass values to methods We have looked at the distinction between class variables and instance variables and at the difference between class methods and instance methods

A summary You should now be familiar with the following JAVA keywords and operators and their use in developing classes and methods: class, private, public, protected, static, void new, return The dot operator “. ”
- Slides: 63