02/24/2020 Review of Previous Lesson State as many Vocabulary words and Learning Objectives that you remember from the last lesson as you can. Remember to grade yourself from 0 - 3. 1 02/24/2020 Object Orientated Programming Paradigm (OOP) Own Classes Exercises Complex Classes, Accessor & Mutator methods, Encapsulation, Overriding
2 LEARNING OBJECTIVE Call non-static non-void methods with or without parameters. Designate access and visibility constraints to classes, data, constructors, and methods. Designate private visibility of instance variables to encapsulate the attributes of an object. Define behaviors of an object through non-void methods without parameters written in a class. Define behaviors of an object through void methods with or without parameters written in a class. Define behaviors of an object through non-void methods with parameters written in a class. 3 ESSENTIAL KNOWLEDGE Non-void methods return a value that is the same type as the return type in the
signature. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression. When designing a class, programmers make decisions about what data to make accessible and modifiable from an external class. Data can be either accessible or modifiable, or it can be both or neither. Instance variables are encapsulated by using the private access modifier. The provided accessor and mutator methods in a class allow client code to use and modify data. An accessor method allows other objects to obtain the value of instance variables or static variables. A non-void method returns a single value. Its header includes the return type in place of the keyword void. ESSENTIAL KNOWLEDGE When the return expression is a reference to an object, a copy of that reference is returned, not a copy of the object. The toString method is an overridden method that is included in classes to provide a description of a specific object. It generally includes what values are stored in the
instance data of the object. If System.out.print or System.out.println is passed an object, that objects toString method is called, and the returned string is printed. A mutator (modifier) method is often a void method that changes the values of instance variables or static variables. Methods can only access the private data and methods of a parameter that is a reference to an object when the parameter is the same type as the methods enclosing class. Non-void methods with parameters receive values through parameters, use those values, and return a computed value of the specified type. ESSENTIAL KNOWLEDGE It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification. When an actual parameter is a primitive value, the formal parameter is initialized with a copy of that value. Changes to the formal parameter have no effect on the corresponding actual parameter. When an actual parameter is a reference to an object, the formal parameter is
initialized with a copy of that reference, not a copy of the object. If the reference is to a mutable object, the method or constructor can use this reference to alter the state of the object. Passing a reference parameter results in the formal parameter and the actual parameter being aliases. They both refer to the same object. Data encapsulation is a technique in which the implementation details of a class are kept hidden from the user. ESSENTIAL KNOWLEDGE The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class. Classes are designated public. Access to attributes should be kept internal to the class. Therefore, instance variables are designated as private. Constructors are designated public. Access to behaviors can be internal or external to the class. Therefore, methods can be
designated as either public or private. Within a non-static method or a constructor, the keyword this is a reference to the current objectthe object whose method or constructor is being called. Evaluate object reference expressions that use the keyword this. Java Quick Reference - Accessible methods from the Java library that may be included in the exam Class Constructors and Methods double pow(double base, double exponent) double sqrt(double x) Explanation Math Class Returns the value of the first parameter raised to the power of the second parameter
Returns the positive square root of a double value 8 02/24/2020 Write your own programs: Write your own programs from scratch. Of course you should use previous programs for reference, but write your code from scratch (do not copy and paste). 9 02/24/2020 Cone Objects 1 How would you describe a Cone (in
words) to a young child who doesnt know what one is? Which properties (instance variables) are the basic properties of a right circular cone, such as the one pictured? Why do you think the other properties of a Cone should not be instance variables? Which data type should these instance variables be for a Cone class? h r Continued on the next slide. 10
02/24/2020 How many instance variables should be used? Typically you should use the minimum number of instance variables that describe an object. No instance variable should be reliant on another. If a quantity can be calculated from existing instance variables it is best to provide a method that does the calculation and use it when needed. Not make them into instance variables. If an instance variable is reliant on the value of another, this can result in objects having inconsistent states: e.g. If area & volume are instance variables and lets say the radius is changed, if the area & volume are not recalculated, then the area & volume are now incorrect in relation to the radius of the object. If we do recalculate then we would have to use methods to recalculate them, but then why keep them
as instance variables if we have methods to calculate them? 11 Class Cone Shown in the previous presentations so please write these independently. Instance variables // height of the cone private double height; // radius of the circular base private double radius; Constructor // Creates a new instance of a Cone object with the specified height and radius. public Cone()
New & will be covered later in this presentation Methods 02/24/2020 public double area() // Calculates and returns the area of the cone. public double volume() /* Calculates and returns the volume of the cone. */ See 2 slides ahead for formulae.
public void setHeight() // Changes the height of a cone. public void setRadius() // Changes the radius of a cone. public double getHeight() // Returns the height of a cone. public double getRadius() // Returns the radius of a cone. public String toString() /* Returns the height & radius of a cone for display. */ The setter methods should disallow 0 or tive values and throw an illegalArgument exception.
12 02/24/2020 class ConeTest main() asks the user for or sets (hard wires) a radius & height, constructs a cone object using the values entered by the user above prints out its area and volume 13 02/24/2020 PI, sqrt() & pow(): area of a cone: r(r+hr(r+h2+r2)
Math.PI*radius*(radius + Math.sqrt(Math.pow(height, 2.0) + Math.pow(radius, 2.0))) volume: r(r+hr2h/3 Math.PI* Math.pow(radius, 2) *height/3.0 ? 14 02/24/2020 Printing an object. ConeTest class - main() method: Should be placed after creating an object and before printing its area and volume.
What happens? ? The name of the objects class plus its address will be displayed. 15 02/24/2020 Class Methods Typically contain: Shown in the previous presentations: Calculate and return methods. New & will be covered later in this presentation: Setter/Mutator methods to change instance variables. Getter/Accessor methods to retrieve the values of instance variables.
a toString() method (actually not really new as already discussed in the strings presentation) Notes: 1. The programmer does not have to provide setter/mutator and getter/accessor methods for all instance variables, only ones which he/she anticipates may need to be changed. So if a programmer believes that some instance variables do not to be changed or accessed then the programmer can choose not to provide any setter/mutator or getter/accessor methods for those instance variables (so leaving completely hidden from other programmers who use these classes). 16 Reminder 02/24/2020 Object class in Java The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
? 17 Reminder 02/24/2020 String toString() object toString method String object All objects inherit the toString() method of the Object class, so if a programmer defined object is displayed and its class does not override the toString() method, toString() of the Object class is used:
? The name of the objects class plus its address is displayed, which is mostly useless to the user or even the programmer. 18 Reminder 02/24/2020 Overriding A language feature that allows a subclass or child class to provide a method of the same signature as one in a super/parent class, so that a different more appropriate implementation of a inherited method can be used.
? 19 Reminder 02/24/2020 Rules for Method Overriding 1. The argument list (signature) should be exactly the same as that of the overridden method. 2. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. 3. If a method cannot be inherited, then it cannot be overridden. ? 4. The access specifier for an overriding method can allow more, but not less, e.g. private methods
access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. 5. Constructors cannot be overridden. 20 Reminder 02/24/2020 Overriding String toString() object toString method String object
So if objects from a class are to be displayed, the toString() method should be overridden to return any output a programmer wishes it to. ? Typically this means the values of all instance variables but for programmer defined classes, the programmer is free to decide. 21 02/24/2020 Cone Objects 1 Cone class public String toString() Returns the height & radius of a cone for display.
main() method: prints out a cone objects radius & height 22 02/24/2020 Cone Objects 1 Cone class: ConeTest class - main() method: 23 Accessing & Changing Instance Variables 02/24/2020
ConeTest class - main() method: Should be placed at the end of main() and removed once you have answered the question below. What happens? Why? Why is this actually a good thing? It wont compile because the instance variables are private, so access is restricted to within the same class only. This is actually a good thing because ?setting the radius to 0 should not be allowed anyway. 24 02/24/2020 Encapsulation
Hiding the details of an object from the other parts of a program. Basically, the previous discussions regarding the use of private and setter/getter methods. The object can be used only through its access methods, which are carefully written to keep the object consistent and secure (careful access control). Makes an object look like a black box: The insides of the box are hidden from view. Controls are on the outside of the box. The user can change the operation of the box only by using the controls. The usual example of this is a TV set where the inner workings are sealed in a box. The user interacts with the set using some well-defined controls. The controls are sometimes called the user interface. In object oriented programming, programmers try to make the interface to the object simple and useful. The inner workings of the object should be made private. 25
02/24/2020 Cone Objects 1 Cone class public void setHeight() changes the height of a cone public void setRadius() changes the radius of a cone public double getHeight() returns the height of a cone main() method: changes the radius reprints the new radius only changes the height
reprints the new height only public double getRadius() returns the radius of a cone 26 Cone Objects 1 Cone class: 27 Cone Objects 1 02/24/2020 Cone class:
28 02/24/2020 ConeTest Class main() method // Set radius of a Cone object to something different to what it was constructed with. coneObj1.setRadius(.) ; // Display only the new radius of a Cone object. Use getRadius() // Display the new area and volume of a Cone object. . 29 02/24/2020 ConeTest Class main() method
// Set height of a Cone object to something different to what is was constructed with. coneObj1.setHeight (.) ; // Display only the new height of a Cone object. Use getHeight() // Display the new area and volume of a Cone object. . 30 02/24/2020 ConeTest class To summarise the main() method should:
sets the (or asks the user for) radius & height, constructs a cone object prints out its radius & height prints out its area and volume changes the radius reprints the new radius only re-prints the new area and volume changes the height reprints the new height only re-prints the new area and volume 31 Cone Objects 1 02/24/2020
Answer the following questions: 1. 2. 3. 4. Why are the radius and height the only instance variables of a cone? Typically how many instance variables should be used? What must the constructor of the Cone class be named? Why? You were asked to write a separate ConeDriver class with a main() method, is this class used to create an object? 5. Can several objects of type Cone be constructed? 6. Which method changes the height of a Cone? 7. If you use different names for constructor parameters and instance variables, can you use constructor parameter names outside the constructor? Why? (e.g. in methods of the same class or in main() of the ConeTest class - try it if necessary)
8. In the main() method, can you change the instance variables directly without using the setter methods (e.g. cone.height = 4.5)? Why? 9. If there were no setter/mutator methods in the Cone class could the height and radius of a Cone be changed? 10. Why not make the instance variables radius & height public ? 11. Are the area and volume of the cone part of a Cone objects state? Why? 12. What does toString() of the Cone class do to toString() of the object class? Explain. 32 02/24/2020 Cone Objects 2 Change the main() method in the previous program so that it creates 2 objects in the code (rather than asking the user or using variables set /hard wired by the programmer) stored in 2 different reference variables which are printed out, followed by their areas and volumes.
e.g. Cone cone1 = new Cone( 2.5, 5.8 ); .... Cone cone2 = new Cone( ..., ... ); . Continued on the next slide. 33 02/24/2020 Cone Objects 2 Answer the following questions: 1. There are two objects, but each uses the same names for its instance variables! How does area() know which ones to use? 2. Do the instance variables of an object hold values for the lifetime of the object? How? Where?
3. Do the parameters of a constructor hold values for the lifetime of the object? Explain why? 34 02/24/2020 Cone Objects 3 Change the main() method in the previous program so that it creates 2 objects in one reference variable and then prints them both out, followed by their areas and volumes. e.g. Cone cone = new Cone( 1.2, 4.56 ); ..... cone = new Cone( 3.0, 1.2 );
35 02/24/2020 Cone Objects 3 Answer the following question: What happens to the first cone when a reference to a 2nd Cone object is assigned to the same reference variable as the 1st? Why? e.g. Cone cone = new Cone( 1.2, 4.56 ); ..... cone = new Cone( 3.0, 1.2 ); 36 02/24/2020
Cylinder Create a class for circular cylinders. Create a testing class CylinderTester to verify that your code works. Decide on the instance variables that the class needs and makes them private. Include setter and getter methods for them. Include methods for the volume and surface area of a cylinder. The volume of a right circular cylinder is the area of its base times its height: V = r(r+hr2h In java = Math.PI The surface area is the area of its base, plus the area of its top, plus the area of the rectangle formed by its flattened out side: V = 2r(r+hr2 + 2r(r+hrh Also include a toString() method. main() in a Test class should request at least one to be created and use all available methods from Cylinder class at least once.
37 02/24/2020 Bank Account Which instance variables should be part of a bank account? Which methods should a bank account have? Continued on the next slide. 38 02/24/2020 Bank Account Instance variables: Account number
The account number should be a String reference because it is not expected to take part in arithmetic operations. Sometimes account numbers contain dashes or other nondigit characters. Name of account holder String Current balance The balance is kept in terms of cents, so should be an int. Initial balance should be passed on object creation. useCount To keep track of how many times the balance of the checking account has been altered as a security measure.
Constructor Create the object; initialize the instance variables. Methods Accept a deposit Adds an amount (in cents) to the current balance. The current balance can be negative or positive. Process a cheque Subtracts the amount of the cheque from the current balance. Overdrafts are allowed, so the balance can become negative. However, if the balance is less than $1000.00 before the cheque is processed, $0.15 is charged for each cheque.
Get the current balance incrementUse() Note: We will not worry about a cash withdrawal method from this account. Keeps track of how many times each the balance of checking account has been altered as a security measure. toString() Returns the account number, owners name, the
balance of the account number & useCount. Continued on the next slide. 39 02/24/2020 Bank Account 1 Use encapsulation as much as possible, you decide what is public and what is private appropriately. Write a separate class with a main() method to construct 2 accounts and which uses all methods and moves money from one to the other. e.g. cheque written from 1 is followed by a cheque deposited in the other. account1.processCheque(amount); account2.deposit(amount);
Or account1.processCheque(1000); account2.deposit(1000); 40 02/24/2020 Bank Account 1 Answer the following questions: 1. Why is the fact that the following statement does not work in main() a good thing? From a Java programming point of view, what is actually stopping this from being possible? account1.balance = 10000000; 2. How can you change the balance in a CheckingAccount object? 3. Lets say another bank charges only 10 cents per cheque for accounts with a balance of more that $500. Our bank needs to do the same in order to keep its customers. How hard will it be to make that change? Would this be the same if the balance was public?
4. Will the following line in main() compile? Why? bobsAccount.incrementUse() //Assuming bobsAccount is a reference variable for an account object. 5. Should you make useCount and incrementUse() public so that they can be used in main()? Explain. 41 02/24/2020 Bank Account 1 Answer the following questions: 6. What does the useCount keep track of: The number of times an individual object has had its balance changed, or The number of times the entire class has been used? In the processCheque() method (try the following lines if necessary): 7. Will the following declaration compile? Why?
int amount; /* Assuming that you have used this variable name as formal parameter in the header of the processCheque method. */ 8. Explain why the following declaration will compile but causes problems: int balance = 0; 42 02/24/2020 Bank Account 2 In main() declare a 3rd reference variable to hold the 1st account which was created (the same as the account held in the 1st reference variable). Use == to demonstrate that they both point to the same object. Each reference variable is sometimes called an alias. e.g. CheckingAccount account1 = new CheckingAccount( "123", "Bob", 100 );
CheckingAccount account2 = new CheckingAccount( "456", "Jill", 900 ); CheckingAccount account3; . account3 = account1; .. // account1 == account 3 43 02/24/2020 Bank Account 2 Answer the following questions: 1. How many CheckingAccount objects are there? 2. How many object reference variables are there? 3. Find out the standard English language meaning of alias and then try to explain why this term is used for reference variable names.
44 Reminder 02/24/2020 Overloading Overloading is when two or more methods of a class have the same name but have different parameter lists. When a method is called, the correct method is picked by matching the actual parameters in the call to the formal parameter lists of the methods. ? 45 02/24/2020
Bank Account 3 Overload the processDeposit() method in the BankAccount class as 2 processDeposit() methods are now needed: 1. The original one for ordinary deposits, for which there is no service charge. 2. A new one for other deposits, for which there is a service charge. Make sure main() demonstrates the use of both versions of the processDeposit() method. 46 this: as a reference to the current object 02/24/2020 Bear Hugs:
One bear can hug another bear. Total number of hugs increases by 1. Each bears numHugs increases by 1. If a bear hugs itself then the total number of hugs and its own numHugs should not change. 47 4. Descriptions such as the implicit parameter this. 02/24/2020 What happens
that shouldnt? 48 4. Descriptions such as the implicit parameter this. 02/24/2020 mama only gave & received 3 hugs but because she hugged herself, she got 2 more hugs. A bear should be allowed to cheat by hugging themselves! How can we solve this? 49
4. Descriptions such as the implicit parameter this. 02/24/2020 Now mama hugging herself is not counted. Now a bear hugging itself has no effect on totalHugs or numHugs of each bear. If a bear is hugging another bear then . otherwise dont do anything. 50 02/24/2020
Grade yourself Grade yourself on the vocabulary and learning objectives of the presentation. 51
Steps to introducing a quality culture. Step 1: Set up discussion groups of front line staff with the specific purpose of identifying the three most common complaints by customers from a front line perspective. Step 2: Conduct workshops with front...
Trials must register at or before the onset of patient enrolment. The clinical trial registration number should be included at the end of the abstract of the article. A clinical trial is defined as any research study that prospectively assigns...
Theoretical capacity. Level of use unconstrained by management. 2. Operational capacity. Level of use under current constraints. 3. Group size. No. of persons typically attending together. Related to period of time. 4. Session. Typical event - e.g. booking, game, performance....
Writing, Chemistry and the Four Skills: Trends and Directions Steven Graham Language Center Udon Thani Rajabhat University Thailand Writing, Chemistry and the Four Skills: Trends and Directions Introduction Background to English for Specific Purposes (ESP) and this study The move...
Beltane May 1st Retold by Lin Donn Illustrated by Phillip Martin May Day is an ancient holiday. But nobody knows who invented it. It's that old. Some people believe the ancient Romans "invented" the May Pole to honor their gods.
Ready to download the document? Go ahead and hit continue!