1 / 63

CMP-MX21: Lecture 6 Objects & Methods 1

CMP-MX21: 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.

donagh
Download Presentation

CMP-MX21: Lecture 6 Objects & Methods 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CMP-MX21: Lecture 6Objects & Methods 1 Steve Hordley

  2. 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 JAVA is an object oriented programming (OOP) language. To use it properly we need to understand what this means

  3. 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.

  4. 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

  5. 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.

  6. 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

  7. 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

  8. 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.

  9. 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).

  10. Class: bank account Account number Account holder Account balance Make Deposit Make Withdrawal Calculate Interest 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: These are the class attributes or states. These are the behaviours or actions which are associated with the bank account

  11. Coding the class in JAVA class bankAccount { // Class variables (data) private String accountName; private String accountHolder; private float accountBalance; // Class actions (methods) … }

  12. Coding the class in JAVA class bankAccount { ... } 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 accountName; private String accountHolder; private float accountBalance;

  13. The private keyword Note that the variable declaration here is modified with the private keyword: private String accountName; 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

  14. 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

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

  16. 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.

  17. Object 1 13456302 D. J. Smith 350.23 Class: bank Account Account number Account holder Account balance Object 2 Object 3 63817845 R. G. Hunt 5034.62 49714294 W. H. Freeman 534.60 Make Deposit Make Withdrawal Calculate Interest 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:

  18. 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 myProgram { public static void main( String [] args ) { bankAccount myBankAcct; myBankAcct = new bankAccount(); } Call to the class constructor method Class name Object name

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

  20. Creating objects from classes It is the second line which actually creates the bankAccount object: mybankAcct = new bankAccount(); 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?

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

  22. 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 myProgram { public static void main( String [] args ) { myMethod(); } This line “calls” the method with name myMethod

  23. A word about methods Our code to create a bank account object contains a call to a method: mybankAcct = new bankAccount(); This method called bankAccount() 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

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

  25. 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 myProgram { public static void main( String [] args ) { bankAccount myBankAcct, anotherAcct; myBankAcct = new bankAccount(); anotherAcct = new bankAccount(); } Each time we create (construct) an object, memory is set aside for it by the constructor function:

  26. null null null null 0.0 0.0 Creating multiple objects Acct. no. myBankAcct Acct. holder Acct. balance Acct. no. Acct. holder anotherAcct Acct. balance

  27. 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

  28. 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 bankAccount { // Class variables (data) private String accountName; private String accountHolder; private float accountBalance; private float interestRate; // Class actions (methods) } interestRate variable added here

  29. null null 0.0 0.0 Class variables Now, each time we create (construct) a bank account object JAVA reserves space for four variables: Acct. no. myBankAcct Acct. holder Acct. balance 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.

  30. Class variables We achieve this in JAVA by defining interestRate to be a class variable: private static float interestRate; 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.

  31. 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 bankAccount objects, there will still be only a single interestRate variable.

  32. 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 bankAccount class will be saved in a file called bankAccount.java To use the class in our programs we must first compile the class: C:\myjavacode>javac bankAccount.java On successful compilation the JAVA compiler will produce a file called bankAccount.class

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

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

  35. 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, bankAccount.class is not executable because it doesn’t contain a main method. To use the methods in bankAccount.class we must call them from other classes.

  36. 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 bankAccount objects. To make the class more useful we need to add methods to it which allow us to change the attributes of a bankAccount e.g. to change an account balance. To do this we need to understand a little bit more about methods.

  37. 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 getBalance( ){ return accountBalance; }

  38. More about methods The first line begins the definition of a new method called getBalance: public float getBalance( ) The method name: getBalance 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

  39. 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 bankAccount objects and then queries their balance using getBalance(). 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.

  40. 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, bankAccount. Some methods don’t return any variable this is indicated using the void keyword: public void myMethod( )

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

  42. The return keyword 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 accountBalance; Here return is followed by the variable name accountBalance which has a type of float. This matches the return value of the method getBalance().

  43. Calling a method To use the getBalance method we would write the following piece of code: class myProgram { public static void main( String [] args ) { float theBalance; bankAccount myBankAcct; myBankAcct = new bankAccount(); theBalance = myBankAcct.getBalance(); System.out.println(“The balance is ”+theBalance); }

  44. Calling a method The method is called using the dot operator .: myBankAccount.getBalance() In English this statement means call the method getBalance() for the object myBankAccount When JAVA reaches this statement it executes the method getBalance(). This method simply returns the value of accountBalance for the relevant object. The relevant object is the object for which the method is called: myBankAccount in this case.

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

  46. 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 makeDeposit( float amount ){ if (amount >= 0 ) accountBalance += amount; else System.out.println(“Cannot deposit a negative amount”); }

  47. The method definition public void makeDeposit( float amount ){ The method doesn’t need to return a value so we use the keyword void We want to be able to call this method from outside the class definition so we define it public. 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

  48. Calling a method with arguments When calling a method with arguments we must pass all the arguments which the method requires: class myProgram { public static void main( String [] args ) { float theBalance; bankAccount myBankAcct; myBankAcct = new bankAccount(); myBankAcct.makeDeposit(500.63f); theBalance = myBankAcct.getBalance(); System.out.println(“The balance is ”+theBalance); }

  49. Calling a method with arguments myBankAcct.makeDeposit(500.63f); 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 theAmount = 500.63f; myBankAcct.makeDeposit(theAmount);

  50. 500.63 500.63 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 theAmount = 500.63f; myBankAcct.makeDeposit(theAmount); theAmount Main program calls the method makeDeposit public void makeDeposit(float amount) When makeDeposit is called, JAVA creates a new variable: amount and initialises its value to be the value of theAmount amount

More Related