introduction to objects and object-oriented...

94
Instructor: Azhar Introduction to Objects and Object-Oriented Programming Week 4

Upload: others

Post on 14-Jul-2020

28 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

Instructor: Azhar

Introduction to Objects and

Object-Oriented Programming Week 4

Page 2: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

2

Agendas

Language FeaturesJava DataTypes

Objects and Classes Access ControlClass Methods and Variables

Page 3: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

3

Java Data TypesPrimitive Data TypesReference Types

Page 4: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

4

Primitive Data TypesThe usual suspects:

byte, short, int, longcharbooleanfloat, double

The usual operators and rules apply mostly

Page 5: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

5

Page 6: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

6

Reference Types (1)Can't write about objects without referring to themReference value: the only way to refer to an objectJava has:

reference values (or just references)reference expressionsreference variablesassignment of references

Page 7: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

7

Declarations, Variables, Assignments

C-like rules apply for the most part

Type specifier followed by identifier list

Page 8: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

8

Number typesint: integers, no fractional part1, -4, 0

double: floating-point numbers (double precision)0.5, -3.11111, 4.3E24, 1E-14

Page 9: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

9

Syntax: Constant DefinitionExample:  Purpose:   In a method:

final typeName variableName= expression ;In a class:

accessSpecifier static final typeName variableName = expression;

Example:final double NICKEL_VALUE =0.05; public static final double LITERS_PER_GALLON =3.785;

Purpose:To define a constant of a particular type

Page 10: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

10

Division and Remainder

/ is the division operator If both arguments are integers, the result is an integer. The remainder is discarded 7.0 / 4 = 1.757 / 4 = 1 Get the remainder with % (pronounced "modulo")7 % 4 = 3

Page 11: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

11

Mathematical Functions

closest integer to xMath.round(x)

sine, cosine, tangent (x in radian)

Math.sin(x), Math.cos(x), Math.tan(x)

natural logMath.log(x)

exMath.exp(x)

power xyMath.pow(x, y)

square rootMath.sqrt(x)

Page 12: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

12

Syntax: Static Method CallClassName. methodName( Tparameters)

Example:Math.sqrt(4)

Purpose:To invoke a static method (a method that

doesn'toperate on an object) and supply its

parameters.

Page 13: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

13

Type ConversionIn assignment, types must match.double total = "a lot"; // no Use “cast” (int) to convert floating-point values to integer values:int pennies   = (int)(total * 100);Cast discards fractional part.

Use Math.round for rounding:int dollar =   (int)Math.round(total);

Page 14: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

14

Syntax: Cast

(typeName)expression

Example: (int)(x + 0.5)

(int)Math.round(100 * f)

Purpose:To convert an expression to a different type

Page 15: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

15

Objects

Only accessed via reference values

Rectangle r1= new Rectangle( );

Not seen— we (the programmers) only

get references to them and send them

messages.

r1.getArea();

Page 16: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

16

Objects Can NOT Beassigned to a variable

int x=Rectangle new Rectangle();the value of an expression

new Rectangle()= x+y; passed as an argument in a message to an object

r1.setArea( new Rectangle());returned by an object responding to a messageDeclared

Rectangle r1; // Does not create the object.

Page 17: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

17

But References Can Be

assigned to a variablethe value of an expressionpassed as an argument in a message to an objectreturned by an object responding to a messagedeclared

Page 18: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

18

Different Reference Types

References to objects of different classes are different types

Every class implicitly defines a distinct reference type

Page 19: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

19

References Are Not Pointers

can't take "address" of object— can not refer to object without referencecan’t do arithmetic with referencesJava has no pointers

Page 20: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

20

What's The Use Of References?

only way to access an objectonly way to send a message to an object

Page 21: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

21

Messages: SendingMessage Form:

methodName(argument1, argument2, …, argumentN)

Sending a Message (Form):

reference . message

Page 22: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

22

Messages: Response From Receiver

value

send message form can be used in expression

often the right side of an assignment statement

can be primitive data OR a reference to an

object

void

Page 23: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

23

Java Pre-defined Classes

Huge number of predefined classesutlity, I/O, GUI, network, time/day, database, math, etc.

PrintStream class:println(string), print(string)

String class:toUpperCase, trim, substring, indexOf, etc.

File classdelete, renameTo

Page 24: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

24

Java Pre-defined Objects

System.out, System.err, System.inString constants

Page 25: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

25

Sample Code 1String s;

int i=0, k;

s = "hello, world";

k = s.length();

while (i<k-1) {

System.out.println(s.substring(0,i+1));

i++;

}

Page 26: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

26

Cascading Messages

String s;

s = "Hello".concat(" World").toUpperCase();

System.out.println(s);

Page 27: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

27

Creating Objects

new keywordconstructor + argumentsexpression's value is reference to create object

Page 28: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

28

Creating And Using An Object: Example

File junk;junk = new File("garbage");junk.delete();

Page 29: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

29

Class Definitions

class NameOfClass {

method definitions (including constructors)

instance variable declarations

}

Page 30: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

30

Method Definitions

similar to function definitionsadditional keywords: public or privateoptional keyword: staticoptional phrase: throws SomeKindOfException

Page 31: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

31

Class Definition Example 1 class Laugher4 {

public Laugher4(String defaultSyl) {default = defaultSyl;

}

public void laugh() {System.out.println(default);

}

private String default;}

Page 32: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

32

Class Definition Example 2 class Laugher2 {

public Laugher2() { default = "ha"; }

public Laugher2(String defaultSyl) {default = defaultSyl;

}

public void laugh() {System.out.println(default);

}

public void laugh(String syl) {System.out.println(syl);

}private String default;

}

Page 33: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

33

Signatures and Overloading

Signature: method name + argument typesOverloading: methods of the same name but different signaturespublic Laugher2() { public Laugher2(String defaultSyl) {public void laugh() {public void laugh(String syl) {

Page 34: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

34

A Name Classclass Name {

private String first, last, title;

public Name(String first, String last) {this.first = first;this.last = last;

}public String getInitials() {

String s; // M Azhars = first.substring(0,1); // Ms = s.concat("."); //M. s = s.concat(last.substring(0,1));//M.As = s.concat(".");//M.Areturn s;

}

Page 35: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

35

Name Class (2) public String getLastFirst() {

return lastName.concat(", ").concat(firstName);}

public String getFirstLast() {return first.concat(" ").concat(last);

}

public void setTitle(String newTitle) {title = newTitle;

}

Page 36: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

36

Name Class (3)public static Name read(BufferedReader br)

throws Exception {String first, last;first = br.readLine();last = br.readLine();return new Name(first,last);

}

}

Page 37: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

37

Using The Name Classpublic class TestName{ public static void main(String [] args){BufferedReader br = new BufferedReader( new InputStreamReader(

System.in)); Name n; n = Name.read(br); System.out.println(n.getInitials());}

}

Page 38: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

38

Class Variables: StaticAlthough a class is not an object, a class can have both class variables and class methods.Class variables and class methods can exist whether or not any object is created. Class variables and class methods are indicated with the keyword static.

Page 39: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

39

Static (Class) MethodsA class/static method, as we have already seen, is a method

that: • exists as a member of a class, • may be invoked using either the class name or the

name of an object, • may not access instance variables, (Since class

methods may be invoked regardless of whether or not any object have been created, object/instance variables cannot be accessed by static methods.)

• is often used when it is important to know how many class instances exist or to restrict the number of instances of a class.

Page 40: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

40

Static (Class) VariablesIf a class contains a static variable then:

• All objects/instances of the class share that variable.• There is only one version of the variable defined for the whole class.• The variable belongs to the class.• The variable exists regardless of whether or not any objects have been created.• The variable may be accessed using either the class name or an object name, if an object has been created.

Example:Static or class variables are often used for constants. The Math class contains two class constants: Math.PI and Math.E ( approximate value: 2.71828).

Page 41: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

41

Static

The Java System library contains many class/static methods. The methods of Math are all static as are the (final) variables. Of course, allowing static methods and variables is contrary to the principles of object-oriented programming since Java is providing a mechanism for what amounts to global variables and methods!

Page 42: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

42

Static

The following simple class contains two class/static variables:

• The variable count keeps track of the number of Circle objects that have been created. One version of count exists for the entire class. All objects access this same variable.

• The static variable pi is a constant. Notice the keyword final. Also note that pi is declared public so that any other class may access it as Circle.pi.

Page 43: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

43

Example

Page 44: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

44

Test Driver

Page 45: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

45

Explanation

The class method, getCount(), returns the number of Circle objects that have been created.Notice that getCount() accesses count – a class/static variable. Remember: a static method cannot access an instance variable, since instance variables may not even exist.The example also illustrates use of the keyword this. Sometimes the parameter has the same name as one of the instance variables. To differentiate between the parameter and the private variable, use the keyword this. As in C++, this is a reference to the invoking object.

Page 46: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

46

Scope and Lifetimesobjectslocal (method) variables and parametersinstance variablesclass variables

Page 47: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

47

Objects and ClassesObject: entity that you can manipulate in your programs (by invoking methods) Each object belongs to a class Class: Set of objects with the same behavior Class determines legal methods"Hello".println() // Error"Hello".length() // OK

Page 48: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

48

Syntax: Object Constructionnew ClassName(parameters)

Example:new Rectangle(5, 10, 20, 30)new Car("BMW 540ti", 2004)

Purpose:To construct a new object, initialize it with the construction parameters, and return a reference to the constructed object.

Page 49: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

49

Object VariablesDeclare and optionally initialize:Rectangle cerealBox = new Rectangle(5, 10, 20, 30);Rectangle crispyCrunchy; Apply methods:cerealBox.translate(15, 25);Share objects:r = cerealBox;

Page 50: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

50

Uninitialized and Initialized Variables

Uninitialized

Initialized

Page 51: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

51

Two Object Variables Referring to the Same Object

Page 52: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

52

Syntax: Variable DefinitionTypeName variableName;

TypeName variableName = expression;

Example:Rectangle cerealBox; String name ="Dave";

Purpose:To define a new variable of a particular type

and optionally supply an initial value

Page 53: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

53

Writing a Test ProgramInvent a new class, say MoveTest Supply a main method Place instructions inside the main method Import library classes by specifying the package and class name:import java.awt.Rectangle; You don't need to import classes in the java.lang package such as String and System

Page 54: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

54

Syntax: Importing a Class from a Package

importpackageName.ClassName ;

Example:import java.awt.Rectangle;

Purpose:To import a class from a package for use in a program

Page 55: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

55

File MoveRect.java1 import java.awt.Rectangle; 2 3 public class MoveTest 4 { 5 public static void main(String[] args) 6 { 7 Rectangle cerealBox = new Rectangle(5,

10, 20, 30); 8 // move the rectangle 9 cerealBox.translate(15, 25);10 // print the moved rectangle11 System.out.println(cerealBox); 12 }

Page 56: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

56

A Simple Classpublic class Greeter { public String sayHello() { String message ="Hello,World!";

return message; } }

Page 57: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

57

Method Definitionaccess specifier (such as public) return type (such as String or void) method name (such as sayHello) list of parameters (empty for sayHello) method body in { }

Page 58: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

58

Syntax: Method Implementationpublic class ClassName { ... accessSpecifier returnType methodName(parameterType parameterName,...) { method body } ... } …Continue

Page 59: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

59

…ContinueExample:

public class Greeter { public String sayHello() { String message ="Hello,World!"; return message; } }

Purpose:

To define the behavior of a method A method definition specifies the method name, parameters, and the statements for carrying out the method's actions

Page 60: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

60

Syntax: The return Statement return expression;or return;

Example:return message;

Purpose:To specify the value that a method returns, and

exit the method immediately. The return value

becomes the value of the method call

expression.

Page 61: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

61

Testing a ClassTest class: a class with a main method that contains statements to test another class.

Typically carries out the following steps: Construct one or more objects of the class that is being tested. Invoke one or more methods. Print out one or more results

Page 62: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

62

A Test Class for the Greeter Class

public class GreeterTest {

public static void main(String [] args)) { Greeter worldGreeter = new Greeter();

System.out.println(worldGreeter.sayHello());

}}

Page 63: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

63

Building a Test Program1. Make a new subfolder for your

program. 2. Make two files, one for each class.

3. Compile both files. 4. Run the test program.

Page 64: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

64

Testing with the SDK Toolsmkdir greeter cd greeter edit Greeter.java edit GreeterTest.java javac Greeter.java javac GreeterTest.java java GreeterTest

Page 65: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

65

Instance Fieldspublic class Greeter{

...private String name;

}access specifier (such as private) type of variable (such as String) name of variable (such as name)

Page 66: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

66

Instance Fields

Page 67: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

67

Accessing Instance Fields

The sayHello method of the Greeter class can access the private instance field:public String sayHello(){String message = "Hello, " + name + "!";return message;}

Page 68: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

68

Other methods cannot:public class GreeterTest{public static void main(String[] args){. . .System.out.println(daveGreeter.name); // ERROR}} Encapsulation = Hiding data and providing access through methods

Page 69: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

69

Syntax: Instance Field Declaration

accessSpecifier class ClassName{ ... accessSpecifier fieldType fieldName; ... }

Page 70: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

70

Example:public class Greeter

{ ... private String name; ... }

Purpose:To define a field that is present in every object of a class

Page 71: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

71

Constructors• A constructor initializes the instance variables • Constructor name = class namepublic class Greeter(){ public Greeter(String aName) { name = aName; } . . .}Invoked in new expressionnew Greeter("Dave")

Page 72: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

72

Syntax: Constructor Implementation

accessSpecifier class ClassName { ... accessSpecifier ClassName(parameterTypeparameterName ...) { constructor implementation } ... }

Page 73: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

73

Example:public class Greeter { ... public Greeter(String aName) { name = aName; } ...}

Purpose:

To define the behavior of a constructor, which is used to initialize the instance fields of newly created objects

Page 74: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

74

File Greeter.java1 public class Greeter 2 { 3 public Greeter(String aName) 4 { 5 name = aName; 6 } 7 8 public String sayHello() 9 { 10 String message = "Hello, " + name + "!"; 11 return message; 12 } 13 private String name; 14 }

Page 75: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

75

File GreeterTest.java1 public class GreeterTest 2 { 3 public static void main(String[] args) 4 { 5 Greeter worldGreeter = new Greeter("World"); 6 System.out.println(worldGreeter.sayHello()); 7 8 Greeter daveGreeter = new Greeter("Dave"); 9 System.out.println(daveGreeter.sayHello()); 10 } 11 }

Page 76: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

76

Designing the Public InterfaceBehavior of bank account:

• deposit money • withdraw money • get balance

Methods of BankAccount class:deposit withdraw getBalance

Page 77: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

77

BankAccount Public Interfacepublic BankAccount() public BankAccount(double initialBalance) public void deposit(double amount) public void withdraw(double amount) public double getBalance()

Page 78: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

78

Using the Public Interface• Transfer balance

double amt = 500;momsSavings.withdraw(amt);harrysChecking.deposit(amt);

Add interestdouble rate = 5; // 5%double amt = acct.getBalance()* rate / 100;acct.deposit(amt);

Page 79: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

79

Commenting the Public Interface

/** Withdraws money from the bank account. @param the amount to withdraw */ public void withdraw(double amount) { implementation filled in later }

Page 80: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

80

/** Gets the current balance of the bank account. @return the current balance */ public double getBalance() { implementation filled in later }

Page 81: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

81

Class Comment /**

A bank account has a balance that can be changed by deposits and withdrawals. */ public class BankAccount { ...}

Page 82: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

82

Javadoc Method Summary

Page 83: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

83

Javadoc Method Detail

Page 84: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

84

BankAccount Class Implementation

Determine instance variables to hold object stateprivate double balance

Implement methods and constructors

Page 85: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

85

File BankAccount.java

1 /** 2 A bank account has a balance that can be

changed by 3 deposits and withdrawals. 4 */ 5 public class BankAccount 6 {

Page 86: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

86

7 /** 8 Constructs a bank account with a zero

balance 9 */ 10 public BankAccount() 11 { 12 balance = 0; 13 } 14

Page 87: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

87

15 /**

16 Constructs a bank account with a given balance

17 @param initialBalance the initial balance

18 */

19 public BankAccount(double initialBalance)

20 {

21 balance = initialBalance;

22 }

Page 88: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

88

23 24 /** 25 Deposits money into the bank account. 26 @param amount the amount to deposit 27 */ 28 public void deposit(double amount) 29 { 30 double newBalance = balance + amount; 31 balance = newBalance; 32 } 33

Page 89: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

89

34 /**

35 Withdraws money from the bank account.

36 @param amount the amount to withdraw

37 */

38 public void withdraw(double amount)

39 {

40 double newBalance = balance - amount;

41 balance = newBalance;

42 }

43

Page 90: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

90

44 /** 45 Gets the current balance of the bank account. 46 @return the current balance 47 */ 48 public double getBalance() 49 { 50 return balance; 51 } 52 53 private double balance; 54 }

Page 91: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

91

File BankAccountTest.java1 /** 2 A class to test the BankAccount class. 3 */ 4 public class BankAccountTest5 { 6 /** 7 Tests the methods of the BankAccount class. 8 @param args not used 9 */

Page 92: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

92

10 public static void main(String[] args) 11 { 12 BankAccount harrysChecking = new

BankAccount(); 13 harrysChecking.deposit(2000)14 harrysChecking.withdraw(500)15

System.out.println(harrysChecking.getBalance());

16 } 17 }

Page 93: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

93

Variable TypesInstance fields (balance in BankAccount) Local variables (newBalance in deposit method) Parameter variables (amount in deposit method)

Page 94: Introduction to Objects and Object-Oriented Programmingmqazhar/teaching/java/NOTES/lecture4.pdfobject-oriented programming since Java is providing a mechanism for what amounts to global

94

Explicit and Implicit Parameters

public void withdraw(double amount){ double newBalance = balance - amount; balance = newBalance;}

balance is the balance of the object to the left of the dot:

momsSavings.withdraw(500)means double newBalance = momsSavings.balance - amount;

momsSavings.balance = newBalance;