Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Classes. 2 Class use Classes have so far been used in 1 of 2 ways 1.An object has been created from a class myClass myObject = new myClass(); 2.An existing.

Similar presentations


Presentation on theme: "1 Classes. 2 Class use Classes have so far been used in 1 of 2 ways 1.An object has been created from a class myClass myObject = new myClass(); 2.An existing."— Presentation transcript:

1 1 Classes

2 2 Class use Classes have so far been used in 1 of 2 ways 1.An object has been created from a class myClass myObject = new myClass(); 2.An existing class has been used (built on/ extended) to assemble a new class public class myApplet extends TrainingWheels

3 3 Data types We have two distinct types Fundamental/ Primative (int, char, etc.) Data Structure (Object) Each is created differently: int vat; // The variable vat exists and can be used myClass object1;// The variable object1 can’t be used yet

4 4 Object Variables So far the assumption is that the object variable is the object. This is not the whole story. For reasons of effeciency the object variable does not hold the actual object but the address of the object.

5 5 Object Variables/ Simple Variables int IntegerVariable=0; ExampleClass ObjectVariable; Variable Name Used Memory address stored at Contents of that location IntegerVariable01200 ObjectVariable0140null

6 6 Object Variables ObjectVariable = new ExampleClass(); The contents of ObjectVariable are set to the result of 'new ExampleClass()' which is the address where the object which has just been created is stored at.

7 7 Variable Name Used Memory address stored at Contents of that location IntegerVariable01200 ObjectVariable0140920 LocationContents 01400920 ……. 0920Object of type ExampleClass methods… variables…

8 8 // Declare a variable to an address of an object of ExampleClass ExampleClass objectVariable; ExampleClass anotherObjectVariable; // same as above ExampleClass finalObjectVariable; // same as above // Point 1 // Create an object and place the address in the variable objectVariable objectVariable = new ExampleClass(); // Point 2 // Copy the contents of objectVariable into anotherObjectVariable anotherObjectVariable = objectVariable; // Point 3 // Create an object and place the address in the variable finalObjectVariable finalObjectVariable = new ExampleClass(); // Point 4 // Copy the contents of finalObjectVariable into anotherObjectVariable anotherObjectVariable = finalObjectVariable; // Point 5 class ExampleClass { // methods and variables go here }

9 9 The contents of the variable At pointAre objectVariable1null anotherObjectVariable1null finalObjectVariable1null objectVariable20960 (location assigned by VM) anotherObjectVariable2null finalObjectVariable2null objectVariable30960 anotherObjectVariable30960 (contents of objectVariable) finalObjectVariable3null objectVariableVariable40960 anotherObject40960 finalObjectVariable41060 (location assigned by VM) objectVariable50960 anotherObjectVariable51060 (contents of finalObjectVariable) finalObjectVariable51060

10 10 Example ObjectCreationExample.java

11 11 Matching object variable types // Create an object of type ExampleClass and store it in a variable called anObject ExampleClass anObject = new ExampleClass(); AnotherClass anotherObject = anObject; X ExampleClass anotherObject = anObject;

12 12 Aside-Objects of type Object Sometimes you may wish to store an object but are unconcerned with its type. To do this you can use an object variable of type Object which will hold only the address. ExampleClass anObject = new ExampleClass(); Object objectAddress = anObject; To make use of the object you need to cast it to a variable of the correct type ExampleClass anotherObject = (ExampleClass) objectAddress;

13 13 Passing Objects as parameters We have seen objects being passed as parameters, however given what we now know, what is actually happening? Answer: The contents of an object variable (the address) is copied into a formal parameter. The method can now use the address to get access to the object. This type of parameter passing is called ‘pass by reference’

14 14 Revision – Passing fundamental variables The value of the actual parameter is copied into the formal parameter. This type of parameter passing is called ‘pass by value’.

15 15 public class PassByValueExample extends TrainingWheels { public void entryPoint() { // Setup Variable int actualParameter; // Assign value to variable actualParameter =5; outputOnScreen("Value of actualParameter is "+actualParameter); // Point 1 // Call method with variable doubleIt(actualParameter); // Point 4 // Examine contents of variable to see if changed outputOnScreen("actualParameter after doubleIt = "+actualParameter); } // End entryPoint public void doubleIt(int formalParameter) { // Point 2 // Copy of parameter placed in variable formalParameter // Alter value of variable formalParameter = formalParameter * 2; // Point 3 // Output current value of variable outputOnScreen("Value of formalParameter is "+formalParameter); } // End of double } // End passByValueExample 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

16 16 The value of the variable At point Is actualParameter15 formalParameter1(has not been created yet) actualParameter25 formalParameter25 (copy of contents of actualParameter) actualParameter35 formalParameter310 actualParameter45 formalParameter4(doesn't exist, method finished so deleted)

17 17 Passing objects When passing an object variable the rule does not change. The contents of an object variable (the actual parameter) are copied into the formal parameter (also an object variable). You now have two copies of the address of the object. There is still only ONE object. This means that any alterations carried out on the formal parameter object will also affect the actual parameter.

18 18 public class PassByReferenceExample extends TrainingWheels { public void entryPoint() { ExampleClass exampleObject; // Point 1 // Setup the variable exampleObject to hold an address // Create an object and put its address in exampleObject exampleObject = new ExampleClass(); // Point 2 // Access the object outputOnScreen("Contents of ValueString"); outputOnScreen(exampleObject.getValueString()); // Call the method changeObject with the address of exampleObject changeObject(exampleObject); // Point 5 // Check to see if the contents of exampleObject have changed outputOnScreen("Contents of valueString"); outputOnScreen(exampleObject.getValueString()); } // End entryPoint public void changeObject(ExampleClass receivedObject) { // Point 3 // Copy the reference to an object into the variable receivedObject // Change one of the variables in the object receivedObject.changeString("hello"); // Point 4 // Finish the method } // End changeObject } // End PassByReferenceExample 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

19 19 class ExampleClass { private String valueString="default"; public void changeString(String receivedValue) { valueString = receivedValue; } // End changeString public String getValueString() { return valueString; } // End getValueString } // End ExampleClass

20 20 The value of the variableAt pointIs exampleObject1Null exampleObject20420 (example location of object of type exampleObject) exampleObject.valueString2"default" exampleObject30420 receivedObject30420 (contents of exampleObject) exampleObject.valueString3"default" receivedObject.valueString3"default" exampleObject40420 receivedObject40420 exampleObject.valueString4"hello" receivedObject.valueString4"hello" exampleObject50420 receivedObject5doesn't exist exampleObject.valueString5"hello" receivedObject.valueString5doesn't exist

21 21 Output

22 22 String passing Is a String passed by reference or value (remember a String is treated like a fundamental type but is actually an object)? A String is passed by value (i.e. alterations to the formal parameter do not affect the actual parameter)

23 23 Passing arrays Arrays are actually objects. Therefore if an array is passed as a parameter what is passed is not a copy of the array but the address of the array. Example: See file ArrayPassingTest.java

24 24 ArrayPassingTest

25 25 Returning an object Object addresses can be returned from methods and used. It is quite common to create an object in a method and return its address. The returned address is then placed in an object variable. Example: See file ObjectReturnExample.java

26 26 Example ObjectReturnExample.java

27 27 Objects and == Testing objects for equality using the == does not work as there may be several different attributes which need comparison. If == is applied to object variables then what is tested is the equality of the contents of the object variables, i.e. whether the two addresses are equal. To compare two objects for equality its best to define a method in the class which compares the objects and returns a boolean value if they are equivalent.

28 28 Example class Person { private String name; private String address; public boolean equalObject(Person objectToCheck) { boolean equal=true; if(!(name.equals(objectToCheck.getName())) equal = false; if (!(address.equals(objectToCheck.getAddress())) equal = false; return equal; } // End equalObject public String getName() {} public String getAddress() {} } // End Person

29 29 Example Person john,jim; // Setup john and jim if(john.equalObject(jim)) …

30 30 String and == Sometimes == works for Strings and sometimes it doesn’t (it depends on the compiler). Best not to take any chances and always use.equals

31 31 Constructor A constructor is a special method which is executed only when an object is created. The purpose of a constructor is to setup (or construct) the environment for the object (variable values, etc.) A constructor method is easily recognised as it must: –Have the same name as the class –Not return any type (not even void) –Be declared as public

32 32 Example ConstructorExample.java

33 33 Constructors and parameters A constructor can be passed parameters. This is accomplished by putting the actual parameter in the brackets which form part of the object creation statement: myClass anObject = new myClass(parameter); If a constructor expects a parameter and is not passed one the compiler will refuse to compile the code.

34 34 Example ConstructorExample2

35 35 Inheritance Inheritance is used when you are not happy with a particular class definition and you want to adopt/adapt certain parts of it to suit your purpose.

36 36 Analogy Creating an object – fast food menu – i.e. using an existing class as is Inheriting a class – a la carte menu – i.e. refining/ augmenting an existing class

37 37 Rules A class can inherit only one other class (unlike other OO languages) If you inherit a class with a constructor which requires parameters you must pass these parameters to it.

38 38 Terminology The name for a class which a class inherits is a Parent or Super class. The name for a class which does the inheriting is a Child or Sub class. Example class StockItem extends Record {} StockItem is a child or subclass of Record and Record is a parent or superclass of StockItem.

39 39 Process When one class inherits another it is as if the code in the super class is combined with the code in the subclass. The compiler must be able to find the super class (at the start its easiest to put it in the same directory/ source code file). Import can be used to tell the compiler where the super class is.

40 40 Bank Employee Example Types of Employee Basic type – gardener, cleaner Teller Manager What do they have in common? A Teller is also an employee A Manager is also a Teller (and therefore an Employee) So we can save effort by reusing relevant classes

41 41 Basic Employee class Employee { private String name; private int hourlyWage; public void setupObject(String nameParameter, int hourlyWageParameter) { name = nameParameter; hourlyWage = hourlyWageParameter; } // End setupObject public String getName() { return name; } // End getName public int calculateWages(int hoursWorked) { return (hoursWorked * hourlyWage); } // End calculateWages // Other methods such as changeWages, etc would go here } // End Employee

42 42 Teller class Teller extends Employee { private int totalLodged=0; private int totalWithdrawn=0; public void lodgeMoney(int amountToLodge) { totalLodged += amountToLodge; } // End lodgeMoney public void withDrawMoney(int amountToWithdraw) { totalWithdrawn += amountToWithdraw; } // End withDrawMoney // Other methods such as getTotalLodged, etc would go here } // End Teller

43 43 Manager class Manager extends Teller { private int loansApproved=0; public void approveLoan(int loanAmount) { loansApproved += loanAmount; } // End approveLoan // Other methods such as getLoans etc would go here } // End Manager

44 44 Inheritance diagram Teller Employee Manager

45 45 Object of Type Teller contains Teller Object Employee Object

46 46 Object of Type Manager contains Teller Object Employee Object Manager Object

47 47 Object of type Teller contains Object of type Teller VariablestotalLodged, totalWithdrawn MethodslodgeMoney(int), withdrawMoney (int) Object of type Employee Variablesname, hourlyWage MethodssetUpObject(String, int), String getName (), int calculateWages (int)

48 48 Object of type Manager contains Object of type Manager VariablesloansApproved MethodsapproveLoan(int) Object of type Teller VariablestotalLodged, totalWithdrawn MethodslodgeMoney(int), withdrawMoney (int) Object of type Employee Variablesname, hourlyWage MethodssetUpObject(String, int), String getName (), int calculateWages (int)

49 49 Example Bank.java

50 50 Why is inheritance so important? It allows code to be reused/altered without affecting the original code Problem solutions can be divided into easy to handle sections which are straightforward to assemble (a Lego analogy is often used) Added layers of complexity and functionality can be assembled while compartmentalising the sections.

51 51 Contacting a constructor from a child class If the parent class contains a constructor which requires a parameter them you must write a constructor in the child class whose first instruction is a call to the method ‘super’. The method super should be called with the parameter you wish to send to the parent class constructor.

52 52 Example InheritanceExample.java

53 53 Protected Public - all elements marked with the public modifier can be viewed in the object and from outside. Private - elements marked private can only be viewed in the object. Private methods and variables are not even available to classes which inherit the class which contains them. Protected - protected elements can be viewed from outside an object but only by objects which come from classes which inherit the class which contains the protected element. By inherit we mean that the class is inherited at some point in the collection of parent-child classes used, e.g. the parent of your parent class could contain a protected element which you could then use. These three descriptors are known as visibility modifiers

54 54 What is the function of protected? If you are certain that a variable/ method should be private but are unsure as to whether any child class may need the variable/ method then mark it as protected. Remember by marking the element as protected you are trusting the programmers of the child class not to create problems for the class with the protected element. If you do not wish to trust the other programmers mark all variables private (or setup a protected method which accesses the private variable after going through verification).

55 55 Protected Protected is the default modifier if no modifier present: E.g. class myClass { int value; } value is protected

56 56 Example ProtectedExample.java

57 57 Polymorphism Lit. ‘many shapes’ Basically it is two rules for handling methods with the same name. These rules apply in different circumstances –Overloading rule – applys if two methods with the same name are in the same class –Overriding rule – applys when a parent and a child class both have a method with the same name

58 58 Overloading Two methods can have the same name provided they have different parameters (either different numbers or different types) The compiler can therefore distinguish the calls to the methods

59 59 Overloading public void methodName(int Value) { // Code for this method, version 1 } public void methodName(String Name) { // Code for this method, version 2 } public void methodName(int Value, int Total) { // Code for this method, version 3 }

60 60 Overloading The methods, all called methodName, are regarded as different by the compiler since they all have unique formal parameters. The compiler would decide which method to call based on the context of the call, i.e. the number and or type of the actual parameters. Example methodName(2,3); // would result in version 3 of methodName being called methodName(3); // would call version 1 methodName("Tuesday"); // would call version 2

61 61 Overloading Overloading does not add functionality but allows consistent names to be used for common functions: Example outputOnScreen(String); outputOnScreen(boolean); outputOnScreen(int);

62 62 Overloading OverloadExample.java

63 63 Overloading constructors We saw that a drawback to constructors was that if a parameter was required then a child would have to supply this parameter via a call to a super method. Can overload constructor to remove this requirement but retain feature.

64 64 Overloading constructors class Bank { private int balance; public Bank(int firstbalance) // First constructor for the bank class, takes the initial balance (int) { balance=firstbalance; } // End Bank constructor(int) public Bank() // Second constructor for the bank class, takes no parameter { balance=0; }// End Bank constructor() // Other methods } // End Bank class The form of the object declarations will decide which constructor is called: Bank Gus = new Bank(10); // calls first constructor method Bank Jill = new Bank(); // calls second constructor method

65 65 Overriding We saw that when a class was inherited it was as if the parent code was merged with the child code. You may not want some of the parent code so how do you get rid of it? To replace a method in a parent class simply write a method with the same name + parameters in the child class. When an object of the child class is created the child method will replace or ‘override’ the parent method.

66 66 Overriding Overriding is useful as it allows parent classes to be ‘altered’ without having to erase code. It allows a consistent method name to be used.

67 67 Overriding class Employee { private String DOB; protected int monthlySalary; public int computePay() // Version 1 of computePay { return monthlySalary; } // End computePay // Other methods would go here } // End of class Employee

68 68 Overriding class PartTimeEmployee extends Employee { private int hoursWorkedThisMonth; private int ratePerHour; public int computePay() {// Version 2 of computePay, replaces version 1 in object of this class return(monthlySalary+(hoursWorkedThisMonth * ratePerHour)); } // Other methods would go here } // End class PartTimeEmployee

69 69 Overriding We can declare an object of our new class type: PartTimeEmployee fred = new PartTimeEmployee(); We can call the new computePay method in the new object fred.computePay(); // Version 2 of computePay is executed We can also create an object of the original parent class Employee jane = new Employee(); and call the original computePay method jane.computePay(); // Version 1 of computePay is executed Note that access to the monthlySalary variable defined in the Employee class was needed in the PartTimeEmployee class so this variable was declared as protected.

70 70 Overriding OverrideExample.java

71 71 Static Both a variable and a method can be described as ‘static’ A static element is one which exists independently of an object, i.e. to use a static method you do not have to create an object of the class which contains the method. Static methods are against the idea of objects but are necessary as mechanisms to start programs. They also have other uses.

72 72 Jelly mold analogy If we go back to the Jelly mold we remember that the mold exists but its purpose was to make jellies which could be used (eaten) We can use the mold in a limited way by: –engraving jelly making instructions on it –making a biro mark on it each time we make a new jelly These are static elements (a method & a variable) We therefore have used the class without affecting, or needing, any of the objects. Also none of the objects contain copies of the jelly making instructions or the number of jellies, i.e. they belong to the class (mold)

73 73 Using Static class ExampleStatic { public static int vat; // Declare a static variable // Declare a static method public static int computePrice(int price) { return (price + ((vat * price) / 100)); } // End computePrice } // End ExampleStatic

74 74 Using Static To change the contents stored in a static variable use a statement of the form: ClassName.variable, e.g. ExampleStatic.vat = 20; To access a static method use statement of the form: ClassName.methodName();, e.g. ExampleStatic.computePrice(50);

75 75 Example StaticExample.java

76 76 Interfaces An interface is a definition of a set of methods and their parameters. It does not supply the body of the method or variables. An interface is not a class. What an interface does is force the program that uses (implements) the interface to declare the same method names (with the same parameters and return type) as the interface contains. An interface is a way of making sure a program contains certain agreed methods, this means that you can force users to use consistent names.

77 77 Interfaces An interface is not inherited (using extends) but 'implemented' (using the word implements). When source code which implements an interface is compiled it means that the code contained in the interface is matched against the program which implements the interface. The compiler checks to make sure all the methods mentioned in the interface are contained in the program which implements it. If one or more methods are missing or a methods parameters or return types are different then the compiler will report an error and refuse to compile your program.

78 78 Declaration of interface An interface must be written in a file with the extension java It must be started with the word ‘interface’ and followed by the name of the interface (which matches the name of the file)

79 79 Interface File - Example interface InterfaceTest { public void testMethod(); public int anotherTestMethod(int parameter); } // End of interface

80 80 Using an interface An interface is used by placing the word 'implements' and the name of the interface following the declaration of the class name. You can implement one or more interfaces by separating each interface name with a comma and/ or combine an interface implementation with an extends instruction. The extends is placed before the implements.

81 81 Using an interface class ExampleClass implements InterfaceExample { // Class which must contain methods mentioned in InterfaceExample } class ExampleClass implements InterfaceExample, ProgrammersTemplate { // Class which must contain methods mentioned in InterfaceExample // and those contained in ProgrammersTemplate } class ExampleClass extends TrainingWheels implements InterfaceExample { // Class which must contain methods mentioned in InterfaceExample // and which inherits the TrainingWheels class }

82 82 Example UseInterfaceExample.java

83 83 Layer/ Tiers So far the programs we have seen are usually written in a single class or if another class is used its function is merely to store data. Software in the real world normally takes the form of a number of independent classes, like lego blocks, that can be stuck together in whatever form the designer wishes. Programmers thus write sections or components of a solution and put them together as they go along. Classes (also known as components) can be reused for other problems or even sold as a product in their own right.

84 84 Layer/ Tiers This structure where a solution is made out of connected components is called a layered or tiered approach. This means that distinct parts of the solution are organised into distinct groups, these groups are then put together to form layers. Different layers are responsible for different aspects of the solution and information is passed between the layers.

85 85 Layer/ Tiers There are usually three distinct layers: –The user interface layer is intended to contain all the statements necessary to supply information to and obtain information from the user. The user interface layer may not necessarily process the information or store that information, for these functions it can pass the information to an application layer. –The application layer, sometimes called the business logic or logic layer, is usually responsible for managing the information and performing operations on it, for example retrieving information, computing results, applying rules. – The data layers responsibility is to store or retrieve the data on disk, in memory or in a database.

86 86 Tier Example - Bank For example imagine that you were asked to write an Information System for a bank. The structure for a bank : you meet the teller when you go in the door, they take your particular request and then defer to a manager. The manager then looks up your file to see if you can be granted your request, passes their decision to the teller who will notify you.

87 87 Tier Example - Bank To computerise this would require a User Interface to the system that the tellers could use to create new accounts and to lodge and withdraw money from accounts. This User Interface would use another part of the program which would manage accounts. The layer which manages accounts would effectively replace the manager and therefore carries out business logic. Account information could be stored as objects in the data layer. Therefore we have three distinct sections for our problem, a Graphical User Interface layer, a Business Logic layer and a Data layer.

88 88 Bank Layer nameFunction of this layer GUITo allow the user to input and view information. Specifically: - Create a new account - Lodge money - Withdraw money - Check balance Business Logic/ ApplicationTo receive requests from the GUI and to pass it back the result of those requests. Operations to handle: - Create a new account: Search for an existing account with the same name, if it exists deny request. If number of accounts created exceeds a preset limit deny creation request. - Lodge money: Search to see if the named account exists, if so add the amount supplied to the balance of account and return the new balance, return a message otherwise. - Withdraw money: Search to see if the named account exists, if it does deduct a supplied amount from the account provided there is sufficient funds to meet the withdrawal and return the new balance, refuse withdrawal otherwise. Data / DatabaseHold account name and balance of that account. Operations to handle: - Create new record - Get record information - Store information

89 89 Developing Layers Each layer must be debugged before use Dummy layers can assist development Layers should be as independent as possible There can be multiple objects involved in each layer

90 90 Layers Enter Data Login User Handle data input DataBaseAccount Manager GUI Logic Data Account Object

91 91 Tutorial See the Tiers tutorial

92 92 Tutorial See the Fruit tutorial


Download ppt "1 Classes. 2 Class use Classes have so far been used in 1 of 2 ways 1.An object has been created from a class myClass myObject = new myClass(); 2.An existing."

Similar presentations


Ads by Google