looking inside classes choices week 4. class bodies contain fields, constructors and methods. fields...

21
Looking inside classes Choices Week 4

Post on 19-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Looking inside classes

Choices

Week 4

Page 2: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

• Class bodies contain fields, constructors and methods.

• Fields store values that determine an object’s state.

• Constructors initialize objects.• Methods implement the behavior of objects.• Fields persist (remain) for the lifetime of an

object.• Parameters are used to receive values into a

constructor or method.

Java Class DefinitionsWHAT WE LOOKED AT LAST WEEK

Page 3: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

• Conditional Statements

• Local Variables

Java Class Definitions CONCEPTS COVERED THIS WEEK

Page 4: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Java Class DefinitionsREFLECTING ON OUR TICKET MACHINES

Their behavior is inadequate in several ways:

– No checks on the amounts entered.– No refunds.– No checks for a sensible initialization.

How can we do better?

– We need more sophisticated behavior.

Page 5: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Java Class DefinitionsMAKING CHOICES

public void insertMoney(int amount){ if(amount > 0) { balance = balance + amount; } else { System.out.println("Use a positive amount: " + amount); }}

Page 6: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

if(perform some test) { Do the statements here if the test gave a true result}else { Do the statements here if the test gave a false result}

Java Class DefinitionsMAKING CHOICES

‘if’ keywordboolean condition to be tested - gives a true or false result

actions if condition is true

actions if condition is false‘else’ keyword

Page 7: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Making decisions in Java • This is the code to test whether a

student has passed or failed a module, assuming 40% is the pass mark:

if ( studentMark >= 40 ) {      result = "pass";}

else {      result = "fail";} // end if

Page 8: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

public class Person{ private String name; private int age; private String job; private float salary; 

public Person(String newName, int newAge) { name = newName; age = newAge;

salary = 0.0f; }

Java Class DefinitionsEXAMPLE CLASS CONSTRUCTOR

Page 9: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

if (mark.getAge() == 65) {

mark.changeJob(“RETIRED”);

}

//flow-of-control carries on from here …

Graphically - this is an example of a flow chart

Program - SelectionSELECTION CONSTRUCT: if

yes

nois Mark 40 years old?

retire Mark

//carry on from here …

yes

nois Mark 40 years old?

retire Mark

//carry on from here …

Page 10: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

public void payRise (float percentage)

{

if ( getAge() >= 65 ) {

System.out.println("No pay rise for you!");

}

else {

salary = salary + (salary * percentage)

}

//flow-of-control carries on from here …

}

Program - SelectionSELECTION CONSTRUCT: if

Page 11: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Program - SelectionSELECTION CONSTRUCT: if … else

yes noIs Mark retired?

Increase Mark’s Salarydisplay message

flow-of-control carries on from here!

yes noIs Mark retired?

Increase Mark’s Salarydisplay message

flow-of-control carries on from here!

Page 12: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Improved printTicket()

public void printTicket() { if(balance >= price) { // Simulate the printing of a ticket. System.out.println("##################"); System.out.println("# The BlueJ Line"); System.out.println("# Ticket"); System.out.println("# " + price + " cents."); System.out.println("##################"); System.out.println(); // Update the total collected with the price. total = total + price; // Reduce the balance by the price. balance = balance - price; } else { System.out.println("You must insert at least: " + (price - balance) + " more cents."); } }

Uses if else to check if there are sufficient funds to buy a ticket

Page 13: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

EQUALITY AND RELATIONAL OPERATORS

Example Meaningbalance == price balance equal to pricebalance != price balance not equal to pricebalance > price balance greater than pricebalance < price balance less than pricebalance >= price balance greater or equal to pricebalance <= price balance less or equal to price

Page 14: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Examplesint janet = 44, john = 12;

janet == john john != 12

john <= 12 7 < john

janet > john

janet >= 44

Page 15: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

• The == operator is not a valid way make a comparison of two String objects. It does not compare Strings the way we would expect.

• The String class contains a method that is appropriate. The method returns a boolean, which takes the value true when the string executing the method has exactly that same characters in the same order as the string that is passed as a parameter, and false otherwise. For example

• "hello".equals("hello") returns true• "hello".equals("goodbye") returns false

Page 16: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Logical Operators Logical operator Java Logical operatorcond-1 AND cond-2 &&cond-1 OR cond-2 ||cond-1 EXCLUSIVE OR cond-2 ^ NOT cond-1 !

e.g. if (gender == 1 && age >= 65)

Note the use of the round brackets which MUST surround the whole condition. Extra sets of brackets CAN be used for clarity if desired.

Page 17: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Java Class DefinitionsNESTED SELECTION: if … else

Note that else links with the preceding nearest if statement, from the deepest level of nesting outwards, e.g.

if ( condition1 ) if ( condition2 ) statement1; else statement2;else

statement3;

Q1. If condition1 is true, and condition2 is false, which statement will be executed?

Q2. If condition1 is false, and condition2 is true, which statement will be executed?

Page 18: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Java Class DefinitionsLOCAL VARIABLES

public int refundBalance(){ return balance; balance = 0;}

Why won’t this method compile?

unreachable statement!

Page 19: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Java Class DefinitionsLOCAL VARIABLES

Fields are only one sort of variable.– They store values through the life of an object.– They are accessible by all methods throughout the

class.

Methods can include other (shorter-lived) variables.– They exist only as long as the method is being

executed.– They are only accessible from within the specific

method.

Page 20: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Java Class DefinitionsLOCAL VARIABLES

public int refundBalance(){ int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund;}

A local variable

No visibilitymodifier

Page 21: Looking inside classes Choices Week 4. Class bodies contain fields, constructors and methods. Fields store values that determine an object’s state. Constructors

Required ReadingObjects First With Java – A Practical Introduction using

BlueJ

Reading for this week’s lecture

• Chapter 2

Reading for next week’s lecture

• Chapter 3 (pages 56 – 75)