74
Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

Embed Size (px)

Citation preview

Page 1: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

1

Chapter 5

Ch 1 – Introduction toComputers and Java

Defining Classes and

Methods

Page 2: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

2

Chapter 5

5.1 Class and Method Definitions

5.2 Information Hiding and Encapsulation

5.3 Objects and References

5.4 Graphics Supplement

Page 3: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

3

5.1Class and Method

Definitions

Class Name

Instance Variables

Methods

Page 4: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

4

Java is Object Oriented

It can model any real world object

Page 5: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

5

A class is a blueprint of what an object will look like

Page 6: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

6

The object is just an instance of the class

Page 7: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

7

Object Oriented Programming deals with the creation of objects

and their relationships and interactions

Page 8: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

8

Start by defining the class

Car

- bodyPaintColor: Color- numberOfTires: int

+ getBodyPaintColor(): Color+ setBodyPaintColor(Color color): void+ getNumberOfTires(): int+ setNumberOfTires(int tireCount): void

Use a UML class diagram

instancevariables

instancemethods

Page 9: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

9

Code the class definition

public class Car {

private Color bodyPaintColor; private int numberOfTires; public Color getPaintColor() { return bodyPaintColor; } // end getPaintColor()

public void setPaintColor(Color color) { bodyPaintColor = color; } // end setPaintColor()

public int getNumberOfTires() { return numberOfTires; } // end getNumberOfTires()

public void setNumberOfTires(int tireCount) { numberOfTires = tireCount; } // end setNumberOfTires()} // end Car

instancevariables

instancemethods

Page 10: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

10

An Object consists of data ...

bodyPaintColor Color.GreennumberOfTires 4greenCar

object's memoryfootprint

Page 11: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

11

and operations that store and manage the data

bodyPaintColor Color.GreennumberOfTires 4

greenCar

bodyPaintColor Color.Red

numberOfTires 4

redCar

Class Car methods

methods are shared by all car objects

Page 12: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

12

Each class should be in a separate file

public class Car { // code omitted} // end Car

Car.java

public class Driver { // code omitted} // end Driver

Driver.java

Page 13: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

13

new Creates an instanceof a class

Car myCar = new Car();

Page 14: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

14

Recap

An object is an instance of class

Use new to create an object

Objects have data (instance variables)

Objects offer functionality (methods)

Page 15: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

15

There are two types of methods

Methods that do not return a value (void)

System.out.println("println does not return");

and methods that do return a value

int num = keyboard.nextInt();

Page 16: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

16

Let's see how methods work

Car myCar = new Car();

First create the object

bodyPaintColor null

numberOfTires 0myCar Defaultvalues

Page 17: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

17

You can then call a method to setan instance variable

myCar.setNumberOfTires(4);

bodyPaintColor null

numberOfTires 4myCar

Receiving Object

Page 18: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

18

or a get method to retrieve an instance variable

int tireCount = myCar.getNumberOfTires()

bodyPaintColor null

numberOfTires 4myCar

4

Page 19: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

19

this Demystified

public int getNumberOfTires() { return this.numberOfTires;} // end getNumberOfTires()

public void setNumberOfTires(int tireCount) { this.numberOfTires = tireCount;} // end setNumberOfTires()

Since each method is shared by all the objects, we need to be able to identify the receiving object.

this refers to the receiving object, implicitly.

Page 20: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

20

void Method Definition

public void setNumberOfTires(int tireCount) {

numberOfTires = tireCount;

} // end setNumberOfTires()

Method is accessible by defining class and any other

class

Parameter list can be empty or list parameters

needed

Instance Variable

Page 21: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

21

return Method Definition

public int getNumberOfTires() {

return numberOfTires;

} // end getNumberOfTires()

return type of int Parameter list can be empty or list

parameters needed

Instance Variable

Page 22: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

22

Recap

Methods expose a class's functionality

Call a method on a receiving object

this identifies the receiving object inside the method's definition

Each class is stored in its own .java file

Page 23: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

23

Local variables are defined within a method

public double updateSumAmount(double amount) {

double newSumAmount += amount;

return newSumAmount;

} // end updateSumAmount()

local variable

Page 24: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

24

Methods can definesame name local variables

public void method1() { double someDouble = 0;

// Code omitted

} // end method1()

public void method2() { double someDouble = 0;

// Code omitted

} // end method2()

local to method1

local to method2

Page 25: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

25

5.2Information Hiding and

Encapsulation

Page 26: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

26

A method should hide how it is implemented

I know what the method

does,just not how!

Page 27: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

27

Know "what" a method does, not "how" it does it

Page 28: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

28

Methods can be public

These define the class's interface

Page 29: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

29

or private

These are part of the implementation

Page 30: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

30

Instance Variables are private

They define the implementation

Page 31: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

31

Accessor methods controlaccess to instance variables

Getters retrieve instance variables

Setters set instance variables

Page 32: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

32

Recap

Local variables are defined within a method

Know "what" a method does, not "how" it does it

Public methods define the class's interface

Private instance variables/methods are part of the implementation

Page 33: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

33

Class Deconstructed<Fraction>

Fraction

- numerator: int- denominator: int- reduce(): void

+ getNumerator(): int+ setNumerator(int n): void+ getDenominator(): int+ setDenominator(int d): void+ setNumeratorAndDenominator(int n, int d): void+ add(Fraction f): Fraction+ subtract(Fraction f): Fraction+ multiply(Fraction f): Fraction+ divide(Fraction f): Fraction+ show(): void

Page 34: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

34

Application Deconstructed<Fraction.java>

package fractiondemo;

public class Fraction { private int numerator; private int denominator;

private void reduce() { int u = numerator; int v = denominator; int temp; while (v != 0) { temp = u % v; u = v; v = temp; }// end while numerator /= u; denominator /= u; }// end reduce()

Page 35: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

35

Application Deconstructed<Fraction.java>

public int getNumerator() { return numerator; }// end getNumerator()

public void setNumerator(int n) { setNumeratorAndDenominator(n, denominator); }// end setNumerator()

public int getDenominator() { return denominator; }// end getDenominator()

public void setDenominator(int d) { setNumeratorAndDenominator(numerator, d); }// end setDenominator()

Page 36: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

36

Application Deconstructed<Fraction.java>

public void setNumeratorAndDenominator(int n, int d) { numerator = n; if (d == 0) { System.err.println("ERROR: Invalid parameter (" + d + ") in setNumeratorAndDenonimator"); System.exit(1); } else { denominator = d; }// end if }// end setNumeratorAndDenominator() public Fraction add(Fraction f) { Fraction sum = new Fraction(); sum.setNumeratorAndDenominator(numerator * f.denominator + denominator * f.numerator, denominator * f.denominator); sum.reduce(); return sum; }// end add()

Page 37: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

37

Application Deconstructed<Fraction.java>

public Fraction subtract(Fraction f) { Fraction difference = new Fraction(); difference.setNumeratorAndDenominator( numerator * f.denominator - denominator * f.numerator, denominator * f.denominator); difference.reduce(); return difference; }// end subtract()

public Fraction multiply(Fraction f) { Fraction product = new Fraction(); product.setNumeratorAndDenominator( numerator * f.numerator, denominator * f.denominator); product.reduce(); return product; }// end multiply()

Page 38: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

38

Application Deconstructed<Fraction.java>

public Fraction divide(Fraction f) { Fraction division = new Fraction(); division.setNumeratorAndDenominator( numerator * f.denominator, denominator * f.numerator); division.reduce(); return division; }// end divide() public void show() { System.out.print("(" + numerator + " / " + denominator + ")"); }// end show()}// end Fraction()

Page 39: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

39

Application Deconstructed<FractionDemo.java>

package fractiondemo;

public class FractionDemo { public static void main(String[] args) { Fraction f1 = new Fraction(); Fraction f2 = new Fraction(); Fraction result = new Fraction(); // Set f1 to 1 / 4. f1.setNumeratorAndDenominator(1, 4); // Set f2 to 1 / 2. f2.setNumeratorAndDenominator(1, 2);

Page 40: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

40

Application Deconstructed<FractionDemo.java>

// Output their sum, difference, product and division. result = f1.add(f2); f1.show(); System.out.print(" + "); f2.show(); System.out.print(" = "); result.show(); System.out.println(); result = f1.subtract(f2); f1.show(); System.out.print(" - "); f2.show(); System.out.print(" = "); result.show(); System.out.println();

Page 41: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

41

Application Deconstructed<FractionDemo.java>

result = f1.multiply(f2); f1.show(); System.out.print(" * "); f2.show(); System.out.print(" = "); result.show(); System.out.println(); result = f1.divide(f2); f1.show(); System.out.print(" / "); f2.show(); System.out.print(" = "); result.show(); System.out.println(); }// end main()}// end FractionDemo

Page 42: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

42

Application Deconstructed<FractionDemo.java>

Page 43: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

43

5.3Objects and References

Page 44: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

44

There are two types of variables

Value: Stores the actual value

1

Reference: Stores a reference to the actual value

2

Page 45: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

45

Value types store values

int x = 100; 100x

Page 46: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

46

Reference types store references

Fraction f = new Fraction();

2040

.

.

.

f numerator ?

denominator ?

.

.

.

2040

Page 47: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

47

Lets compare value types

int x = 100; x 100

int y = 200; y 200

x == y ? false

x = y; x 200

y 200

x == y ? true

Page 48: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

48

Now lets compare reference types

f1 == f2 ? false

f1 == f2 ? true

Fraction f1 = new Fraction();f1.setNumeratorAndDenominator(1,2);

f1 200numerator 1denominator 2

200

Fraction f2 = new Fraction();f2.setNumeratorAndDenominator(1,2);

f2 208numerator 1denominator 2

208

f1 = f2;f1 208

f2 208numerator 1denominator 2

208

Page 49: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

49

The solution to the == problem?

Define an equals method

Page 50: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

50

Code Deconstructed<equals method>

public boolean equals(Fraction f) {

return this.numerator == f.numerator && this.denominator == f.denominator;

}// end equals()

Two fractions are equal if both their numerator and denominator values are the same.

Page 51: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

51

Code Deconstructed<equals method>

Fraction f1 = new Fraction();f1.setNumeratorAndDenominator(1, 2);

Fraction f2 = new Fraction();f2.setNumeratorAndDenominator(1, 2);

if (f1 == f2) System.out.println("Both variables refer to the same object");else System.out.println("Each variable refers to a different object"); if ( f1.equals(f2) ) System.out.println("Both objects have the same value");else System.out.println("Each object has a different value");

Page 52: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

52

Code Deconstructed<Object variables as parameters>

Fraction f1 = new Fraction();f1.setNumeratorAndDenominator(1,2);

f1 200numerator 1denominator 2

200

Fraction f2 = new Fraction();f2.setNumeratorAndDenominator(1,2);

f2 208numerator 1denominator 2

208

if (f1.equals(f2) {...}...public boolean equals(Fraction f) {...}

f2 208numerator 1denominator 2

208

f 208

Both the argument (f2) and theparameter (f) point to the sameobject.

Notice how the parameter (f) refers to the same object as the argument (f2) and thus object can be changed from within the method.

Page 53: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

53

Code Deconstructed<Object variables as parameters>

Fraction f1 = new Fraction();f1.setNumeratorAndDenominator(1,2);

f1 200numerator 1denominator 2

200

resetFraction(f1);...

public void resetFraction(Fraction f)

f1 200numerator 1denominator 2

200

f 200

Notice here how the object variable (f) has been assigned a new object, and that f1 stills refers to its original object.

{ f = new Fraction(); f.setNumeratorAndDenominator(1, 1);}

f1 200numerator 1denominator 2

200

f 208numerator 1denominator 1

208

Page 54: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

54

5.4Graphic

Supplement

Page 55: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

55

Graphics class Revisited

The Graphics object defines the client area of the applet window.

Page 56: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

56

Applet Deconstructed<SmileyFaceMethods.java>

package smileyfacemethods;

import javax.swing.JApplet;import java.awt.Color;import java.awt.Graphics;

public class SmileyFaceMethods extends JApplet { // All the geometric constants remain the same // ...

Page 57: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

57

Applet Deconstructed<SmileyFaceMethods.java>

@Overridepublic void paint(Graphics canvas) { // Draw a yellow filled face. drawFace(canvas, X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER, Color.YELLOW); // Draw outline in black. drawOutline(canvas, X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER, Color.BLACK);

Page 58: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

58

Applet Deconstructed<SmileyFaceMethods.java>

// Draw a blue left eye. drawEye(canvas, X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT, Color.BLUE);

// Draw a blue right eye. drawEye(canvas, X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT, Color.BLUE);

Page 59: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

59

Applet Deconstructed<SmileyFaceMethods.java>

// Draw the black nose. drawNose(canvas, X_NOSE, Y_NOSE, NOSE_DIAMETER, NOSE_DIAMETER, Color.BLACK);

// Draw the red mouth. drawMouth(canvas, X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE, Color.RED); }// end paint()

Page 60: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

60

Applet Deconstructed<SmileyFaceMethods.java>

private void drawFace(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.fillOval(x, y, width, height);}// end drawFace()

private void drawOutline(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.drawOval(x, y, width, height);}// end drawFace()

Page 61: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

61

Applet Deconstructed<SmileyFaceMethods.java>

private void drawEye(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.fillOval(x, y, width, height);}// end drawEye()

private void drawNose(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.fillOval(x, y, width, height);}// end drawNose()

Page 62: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

62

Applet Deconstructed<SmileyFaceMethods.java>

private void drawMouth(Graphics g, int x, int y, int width, int height, int start, int swipe, Color color) { g.setColor(color); g.drawArc(x, y, width, height, start, swipe); }// end drawNose()}// end SmileyFaceMethods

Page 63: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

63

Applet Deconstructed< SmileyFaceMethods.java >

Page 64: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

64

init() Vs. paint()

Page 65: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

65

Both have a place in Applets

An applet could have both an init() and paint() or neither (unusual)

Both get called automatically

Paint() repaints controls as needed

Init() initialization before applet starts

Page 66: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

66

Code Deconstructed<Label>

import javax.swing.JLabel;

...

JLabel firstNameLabel = new JLabel("First name: ");JLabel lastNameLabel = new JLabel("Last name: ");

A label is a control for displaying static text in an applet or frame.

Create and add the label in the init() method

Page 67: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

67

Code Deconstructed<Container>

import java.awt.Container;

...

Container contentPane = getContentPane();

A Container is a control that can contain other controls

The applet's ContentPane is one such container

Page 68: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

68

Code Deconstructed<FlowLayout>

import java.awt.FlowLayout;

...

contentPane.setLayout( new FlowLayout() );contentPane.add(firstNameLabel);contentPane.add(lastNameLabel);

A FlowLayout control helps in laying out the controls in a container

Each container can be associated with a FlowLayout.

Page 69: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

69

Application Deconstructed<LabelsDemo.java>

package labelsdemo;import javax.swing.JLabel;import javax.swing.JFrame;import java.awt.Container;import java.awt.FlowLayout;

public class LabelsDemo {

public static void main(String[] args) { JFrame frame = new JFrame();

JLabel salutationLabel = new JLabel("Hello there,"); JLabel nameLabel = new JLabel("Mr. Magoo!");

Container contentPane = frame.getContentPane();

Page 70: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

70

Application Deconstructed<LabelsDemo.java>

contentPane.setLayout( new FlowLayout() ); contentPane.add(salutationLabel); contentPane.add(nameLabel); frame.setSize(200, 100); frame.setVisible(true); }}

Page 71: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

71

Application Deconstructed<LabelsDemo.java>

Page 72: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

72

Application Deconstructed<LabelsAppletDemo.java>

package labelsappletdemo;

import javax.swing.JLabel;import javax.swing.JApplet;import java.awt.Container;import java.awt.FlowLayout;import java.awt.Graphics;

public class LabelsAppletDemo extends JApplet {

private void drawString(Graphics g, String string, int x, int y) { g.drawString(string, x, y); }// end drawString()

Page 73: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

73

Application Deconstructed<LabelsAppletDemo.java>

@Override public void init() { JLabel salutationLabel = new JLabel("Hello there,"); JLabel nameLabel = new JLabel("Mr Magoo!"); Container contentPane = getContentPane(); contentPane.setLayout( new FlowLayout() ); contentPane.add(salutationLabel); contentPane.add(nameLabel); }// end init()

The init() method executes once before applet starts. It displays the two labels, but they do not remain

visible for long.

Page 74: Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

74

Application Deconstructed<LabelsAppletDemo.java>

@Override public void paint(Graphics g) { drawString(g, "Hello to you too!", 50, 100); }// end paint()}// end LabelsAppletDemo

The paint() method is then executed and repaints the applet's content pane

and draws the string.

Notice how the labels never have a chance!