Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

2020-09-30

Advanced Object Oriented


Programming

EECS 2030
F 2020 :: Section C

Advanced Object Oriented


Programming

EECS 2030
Lecture 6 :: CLASS BASICS (constructor, method)

1
2020-09-30

▪ Classes
o class basics
Last lecture
o encapsulation
o fields
o constructors
today
o methods

Recall:
Organization of a Typical Java Program
• one or more files
package 2030.lab0; • zero or one package
import java.util;
name
import java.util; • zero or more import
statements
Class Student {
• one class
int age;
• zero or more fields
(attributes)
public Student()
{…} • zero or more constructors
public int getAge() • zero or more methods
}
{…}

2
2020-09-30

Recall:
()

color

• Class:
▪ A class is a model of a thing or concept
▪ A class bundles together a set of values (data), and valid
operations for these values (methods), into a single unit

data methods

(attributes) (behaviors)

▪ A class is an implementation of a reference type


o Student, Point, …

Classes: implementation of reference type


• Most classes can serve as a blueprint for creating objects
▪ An object is an instantiation / instance of a class
▪ Instantiating objects implies the use of NON-STATIC
features
▪ Objects can each have a unique state
o state: set of current values of all of its non-static fields

q
Imagine we have a class Point2D that can be used to create
-3
instances that represent a location (x, y) where x and y are 8
integers
1
public static void main(String[] args) { 2
p

Point2D p = new Point2D(1,2); // point ( 1, 2) 5


13 r
Point2D q = new Point2D(-3,8); // point (-3, 8)
Point2D r = new Point2D(5,13); // point ( 5,13)
6 }

3
2020-09-30

1 5
Point2D p = new Point2D(1, 2); q -3
8
2 p 13 r
Point2D q = new Point2D(-3, 8);
Point2D r = new Point2D(5, 13);
600 Point2D object

x 1
Point2D(1,2)
y 2

64 client
p 600a
700 Point2D object
q 700a
Point2D(-3,8) x -3 GCH
r 800a
y 8

100 Point2D class Point2D object


800
x Point2D(5,13) x 5
y y 13

1 5
Point2D p = new Point2D(1, 2); q -3
8
2 p 13 r
Point2D q = new Point2D(-3, 8);
Point2D r = new Point2D(5, 13);
600 Point2D object

x 1
Point2D(1,2)
y 2

64 client
p 600a
700 Point2D object
q 700a
Point2D(-3,8) x -3 GCH
r 800a
y 8

100 Point2D class Point2D object


800
x Point2D(5,13) x 5
y y 13

p = null; // object at 600 unreachable, will be garbage collected (later)


‘reference count’ is 0

4
2020-09-30

1 5
Point2D p = new Point2D(1, 2); q -3
8
2 p 13 r
Point2D q = new Point2D(-3, 8); w
Point2D r = new Point2D(5, 13);
600 Point2D object

x 1
Point2D(1,2)
y 2

64 client
p 600a
700 Point2D object
q 700a
Point2D(-3,8) x -3 GCH
r 800a
y 8
w 600a

100 Point2D class Point2D object


800
x Point2D(5,13) x 5
y y 13

Point2D w = p;

1 5
Point2D p = new Point2D(1, 2); q -3
8
2 p 13 r
Point2D q = new Point2D(-3, 8); w
Point2D r = new Point2D(5, 13);
600 Point2D object

x 1
Point2D(1,2)
y 2

64 client
p 600a
700 Point2D object
q 700a
Point2D(-3,8) x -3 GCH
r 800a
y 8
w 600a

100 Point2D class Point2D object


800
x Point2D(5,13) x 5
y y 13

Point2D w = p;
p = null; // object at 600 not unreachable, will not be garbage collected
‘reference count’ is not 0, as w reference it
10

5
2020-09-30

Classes can have both static and non-static


features
• Static: implies lack of instantiation
▪ single versions (fields/methods/etc.) in memory
▪ created at compile time
▪ different usage from non-static. Visited later

• Non-Static: implies instantiation of objects


▪ multiple versions (fields/methods/etc.) in memory
▪ created at run-time q

r
11

11

Recall:
Organization of a Typical Java Program
• one or more files
package 2030.lab0; • zero or one package
import java.util;
name
import java.util; • zero or more import
statements
Class Student {
• one class
int age;
• zero or more fields
public student()
(attributes)
{…} • zero or more constructors
public int getAge() • zero or more methods
} {…}

12

12

6
2020-09-30

Implementing classes ()

() color

• fields: "attributes", "instance variables"


color

▪ Data, state of object

Example: Point2D Class

• consider implementing our own class that represents 2-


dimensional points on a real cartesian plane (Point2D)
▪ a possible implementation would have:
o a field to represent the x-coordinate of the point as a float
o a field to represent the y-coordinate of the point as a float

13

/**
* A simple class for representing points in 2D Cartesian
* coordinates. Every <code>Point2D</code> instance has a
* public x and y coordinate that can be directly accessed
* and modified.
*
* @author EECS2030
*/

package eecs2030.basics;

public class: any client can use


public class Point2D{ this class
public float x;
public float y; public fields: any client
can use these fields directly by name
}

Can we use the class (create object) now?


14 (no constructor, no methods)

14

7
2020-09-30

Using Point2D

Immediate issues with current implementation:

1. initializing the coordinates of the point is inconvenient


▪ clients have to manually set the x and y coordinates

2. manipulating a point is somewhat inconvenient


▪ clients have to manually compute a string representation of the point
▪ clients have to manually compute the distance of two points

3. comparing two points using equals() may result in


unexpected results
▪ Point p1 = new Point(1,2); Point p2=new Point(1,2);
▪ p1.equals(p2); ?

4. poor Information hiding (later)


▪ Data accessible to the public
15

15

Encapsulation
• we can add features to Point2D to make it easier to use
▪ we can add access modifiers to fields to prevent unauthorized
access or manipulation of data (information hiding)

▪ we can add constructors that set the values of the fields of a


Point2D object when it is created

▪ we can (need to) add methods that use the fields of Point2D to
perform some sort of computation
o e.g., calculate distance between two points, or distance to origin
o e.g., translate, rotate or scale a point (w.r.t. an origin)

▪ we are obliged to define certain standard methods like


toStrings(), equals() so that we can display, test and compare
objects in a meaningful way

16

16

8
2020-09-30

Encapsulation

This bundling of data and methods that use


the data into a single unit is known as
ENCAPSULATION

Typically achieved by:


restricting/controlling
access to internal data

allowing interaction through


constructors and methods
(expose only what a client needs)
()

color

17

17

Access Modifiers

public, private, default, protected

18

18

9
2020-09-30

Top level classes


• a top level class is a class that is not nested inside of another class
▪ Point2D is a top level class

• a top level class can have either:


▪ the public access modifier public Class Point2D{…}
o the class is visible to all other classes everywhere

▪ no access modifier default Class Point2D{…}


o called package access;
o the class is visible only inside its own package (and not its
sub-packages) import not help

• cannot be private, protected

19

19

Public access, visible outside package (after import)

20

20

10
2020-09-30

Default (package) access, not visible outside package (even after import)

21

21

Access modifiers on fields (and methods)


Public: The access level is everywhere -- from within the class,
outside the class, within the package and outside the package.

Private: The access level is only within the class -- cannot be accessed
from outside the class..

Default (no modifier): The access level of a default modifier is only


within the package. --- cannot be accessed from outside the
package.

Protected: The access level is within the package + subclass


outside the package.

Class access modifier


take precedence!
• public field in default
class not accessible
outside package
22

22

11
2020-09-30

Access modifiers on fields


• the safe rules of thumb:
▪ a field that represents a constant value can be public
o e.g., PI in java.lang.Math

▪ all other fields should be private

• protected fields appear when using inheritance (later)


23

23

/**
* A better way to implement fields of Point2D
*/

package eecs2030.basics;

public class Point2D{


public class: any client can use this class
private float x;
private float y; private fields: visible only to this class
} .x .y okay only in the class

24

24

12
2020-09-30

// in some other application

package eecs2030.basics;

public class PointMaker {

public static void main(String[] args) {

Point2D p = new Point2D();


no longer possible

p.x = -1.0f;
p.y = 1.5f;
System.out.println("p = (" + p.x + ", " + p.y + ")");

25

25

Encapsulation
• we can add features to Point2D to make it easier to use
▪ we can add access modifiers to fields to prevent unauthorized
access or manipulation of data (information hiding)

▪ we can add constructors that set the values of the fields of a


Point2D object when it is created

▪ we can add methods that use the fields of Point2D to perform


some sort of computation
o e.g., calculate distance between two points, or distance to origin
o e.g., translate, rotate or scale a point (w.r.t. an origin)

▪ we are obliged to define certain standard methods (like


toStrings(), equals() so that we can display, test and compare
objects in a meaningful way

26

26

13
2020-09-30

Recall:
Organization of a Typical Java Program
• one or more files
package 2030.lab0; • zero or one package
import java.util;
name
import java.util; • zero or more import
statements
Class Student {
• one class
int age;
• zero or more fields
public student()
(attributes)
{…} • zero or more constructors
}
public int getAge() • zero or more methods
{…}

27

27

28
Stopped here last time

28

14
2020-09-30

Constructors
• the purpose of a constructor:
▪ to initialize the state of an object
o it should set the values of all of the non-static fields to
appropriate values

• a constructor: public Point2D(…)


▪ must have the same name as the class
▪ never returns a value (not even void)
o constructors are not methods *
▪ can have zero or more parameters

• 3 fundamental types of constructor


▪ No-argument (default) constructor
▪ Custom constructor
▪ Copy constructor
29
* Some consider constructor as a special method
29

No constructors defined?

• a constructor must be called whenever a new object is


created (i.e. in conjunction with the new keyword)
▪ but we did not define any constructor for point2D!

• if a class defines no constructors, then the Java compiler


will silently insert a no-argument (default) constructor

30

30

15
2020-09-30

1. No-argument (default) constructor

• Used to instantiate an object without parameters


▪ the default constructor has zero parameters

▪ the default constructor written by implementer initializes


the state of an object to some well-defined state chosen by
the implementer

▪ the default constructor generated by compiler initializes the


fields to default values based on the type
o primitive-type numeric fields to zero 0 0.0
o primitive-type Boolean fields to false
o reference-type fields to null

31

31

public class Point2D {


private float x;
private float y;

/**
* The default constructor. Sets the x and y coordinate
* of the point to -1.0 and 0.0f.
*/
public Point2D() {
x = -1.0f;
y = 0.0f;
}

//or better:

public Point2D() { Inside a constructor, the keyword


this.x = -1.0f; this is a reference to the object
that is currently being constructed/initialized.
this.y = 0.0f;
32 }

32

16
2020-09-30

public class Point2D {


private float x;
private float y;

/**
* The default constructor. Sets both the x and y coordinate
* of the point to 0.0f.
*/
public Point2D() {
this.x = -1.0f;
this.y = 0.0f;
}

// in main of client class:

Point2D p1 = new Point2D();

33

33

The this Reference:

• During construction, or if a method is run on an object:


▪ Point2D p = new Point2D(); p.getX();
▪ The object being created, or used to invoke a method is
known as the target/context object

• the “this” reference is an implicit reference to the


target/context object
▪ only available within constructors/methods of an instantiated
class
▪ “this” is substituted by the name of the instantiated object

Sometimes necessary:
e.g., to resolve ambiguity between instance variables and
parameters
34

34

17
2020-09-30

public class Point2D {


private float x;
private float y;

/**
* The default constructor. Sets both the x and y coordinate
* of the point to 0.0f.
*/
public Point2D() {
// in main of client class:
this.x
p1. = -1.0f;
p1.
this.y = 0.0f; Point2D p1 = new Point2D();
}

35

35

public class Point2D {


private float x;
private float y;

/**
* The default constructor. Sets both the x and y coordinate
* of the point to 0.0f.
*/
public Point2D() {
// in main of client class:
p2.
this.x = -1.0f;
p2.
this.y = 0.0f; Point2D p1 = new Point2D();
}
Point2D p2 = new Point2D();

36

36

18
2020-09-30

2. Custom constructors
• a class can have multiple constructors but the signatures
(list of parameters) of the constructors must be unique
▪ i.e., each constructor must have a unique list of parameter
types

• Why we need more constructors?


▪ Allows to create objects with different info. E.g., Student,
some enrolled in course, some not yet.
▪ E.g. it would be convenient for clients if Point2D had a
constructor that let the client set the x and y coordinate of
the point upon creation

37

37

public class Point2D {


private float x;
private float y;

/**
* Initializes the x and y coordinate of the point to
* the argument values.
*
* @param x the x coordinate of the point
* @param y the y coordinate of the point
*/
public Point2D (float x, float y) {
x = x;
y = y;
}

Compile?
Working?
Local variable shadows the
38 instance variable

38

19
2020-09-30

this (shadowing)
• there are parameters with the same names as fields
▪ when this occurs, the parameter (smaller scope) has
precedence over the field (larger scope)
▪ we say that the parameter shadows the field
public Point2D(float x, float y) { public Point2D(float x2, float y2) {
x = x; x = x2;
y = y; will compile y = y2;
but nothing change }
39
}

▪ when shadowing occurs you must use this to refer to


the field

public Point2D(float x, float y) {


this.x = x;
this.y = y;
}
this needed to resolve ambiguity between
instance variables and parameters

39

public class Point2D {


private float x;
private float y;

/**
* Initializes the x and y coordinate of the point to
* the argument values.
*
* @param x the x coordinate of the point
* @param y the y coordinate of the point
*/
public Point2D (float x, float y) {
this.x = x;
this.y = y;
} this.x : the field named x of this point
this.y : the field named y of this point
x : the parameter named x of the constructor
y : the parameter named y of the constructor

40

40

20
2020-09-30

Point2D p = new Point2D(-1.0f, 1.5f);

1. new allocates memory for a 64 client


Point2D object (in GCH)
p 600a
2. the Point2D constructor is
invoked by passing the memory
address of the object and the
arguments -1.0f and 1.5f to 600 Point2D
object
the constructor
x -1.0f
GCH
fields 1.5f
3. the constructor runs, setting the y
values of the fields this.x and
this.y

4. the value of p is set to the 700 Point2D


constructor
memory address of the
constructed object this 600a
x -1.0f
parameters
y 1.5f

41

41

Custom constructors
• adding the constructor Point2D(float x, float y) allows the
client to simplify their code
public static void main(String[] args) {
// create a point
Point2D p = new Point2D();

// set its coordinates (fields not public, so cannot do this)


p.x = -1.0f;
p.y = 1.5f;

// get its coordinates (fields not public so cannot do this)


System.out.println("p = (" + p.x + ", " + p.y + ")");

Point2D q = new Point2D ();


q.x = p.x;
q.y = p.y;

}
42

42

21
2020-09-30

public static void main(String[] args) {


// create a point
Point2D p = new Point2D(-1.0f, 1.5f);

// set its coordinates


p.x = -1.0f;
p.y = 1.5f;

// get its coordinates


System.out.println("p = (" + p.x + ", " + p.y + ")");

Point2D q = new Point2D(p.x, p.y);


q.x = p.x;
q.y = p.y;
Point2D r = new Point2D();

}
43

43

Few more notes about customer constructor

• Does not need to set all fields


public Point2D(float x) {
this.x = x;
}

• With customer constructor, compiler will not


generate default constructor for you
unless you
Point2D p = new Point2D(); write default
one

44

44

22
2020-09-30

public class Point2D {


private float x;
private float y;

public Point2D (float x, float y) {


this.x = x;
this.y = y;
}

Point2D p = new Point2D(-1.0f, 1.5f);

Point2D r = new Point2D();


45

45

public class Point2D {


private float x;
private float y;

public Point2D () {
this.x = -1.0f;
this.y = 0.0f;
}

public Point2D (float x, float y) {


this.x = x;
this.y = y;
}

Point2D p = new Point2D(-1.0f, 1.5f);

Point2D r = new Point2D();


46

46

23
2020-09-30

Another example

Range q = new Range(2,3);

Range r = new Range();


47

47

3. Copy constructor
• a copy constructor initializes the state of an object by
copying the state of another object (having same type)
▪ it has a single parameter that is the same type as the class

public class Point2D {


private float x;
private float y;

/**
* Sets the x and y coordinate of this point by copying
* the x and y coordinate of another point.
*
* @param other a point to copy
*/
public Point2D (Point2D other) {
is ‘this’ this.x = other.x; other.x is okay inside
a must?
48 this.y = other.y; class, not okay outside
}
48

24
2020-09-30

Copy constructor
• adding a copy constructor allows the client to simplify
their code

public static void main(String[] args) {


// create a point
Point2D p = new Point2D(-1.0f, 1.5f);

// get its coordinates


System.out.println("p = (" + p.x + ", " + p.y + ")");

Point2D q = new Point2D(p.x, p.y);


q.x = p.x;
q.y = p.y;

49

49

Copy constructor
• adding a copy constructor allows the client to simplify
their code

public static void main(String[] args) {


// create a point
Point2D p = new Point2D(-1.0f, 1.5f);

// get its coordinates


System.out.println("p = (" + p.x + ", " + p.y + ")");

Point2D q = new Point2D(p);


q.x = p.x;
q.y = p.y;
Any aliasing (of
members)?
}

50

50

25
2020-09-30

Summary: 3 types of constructors


public class Point2D {
public float x;
public float y;

public Point2D() {
this.x = -1.0f; Is ‘this’ a
this.y = 0.0f; must?
}

public Point2D(float x, float y) {


this.x = x;
this.y = y; is ‘this’ a
} must?

public Point2D(Point2D other) {


this.x = other.x;
is ‘this’ a
this.y = other.y;
must?
} simplify
51

51

Avoiding Code Duplication


• notice that the constructor bodies are almost identical to
each other
▪ all three constructors have 2 lines of code
▪ all three constructors set the x and y coordinate of the
point

• whenever you see duplicated code you should consider


moving the duplicated code into a method

• in this case, one of the constructors already does


everything we need to implement the other
constructors…

52

52

26
2020-09-30

Constructor chaining
• a constructor is allowed to invoke another constructor
• when a constructor invokes another constructor it is
called constructor chaining
• to invoke a constructor in the same class you use the
this keyword
▪ if you do this then it must occur on the first line of the
constructor body
o but you cannot use this in a method to invoke a constructor

• we can re-write two of our constructors to use


constructor chaining...

53

53

Constructor chaining
public class Point2D {
public float x;
public float y;

public Point2D() {
this.x = -1.0f;
this.y = 0.0f;
}

public Point2D(float x, float y) {


this.x = x;
this.y = y; one of the constructors
} already does everything
we need to implement
public Point2D(Point2D other) { the other constructors…
this.x = other.x;
this.y = other.y; Which one to keep?
}
54

54

27
2020-09-30

Constructor chaining
public class Point2D {
public float x;
public float y;

public Point2D() {
this(-1.0f, 0.0f);

}
invokes

public Point2D(float x, float y) {


this.x = x;
this.y = y;
}
invokes
public Point2D(Point2D other) {
this(other.x, other.y);
}

55

55

Constructor chaining
public class Point2D {
public float x;
public float y;

public Point2D() {
this(-1.0f, 0.0f);
…. // more code is needed
}
invokes

public Point2D(float x, float y) {


this.x = x;
this.y = y;
}
invokes
public Point2D(Point2D other) {
this(other.x, other.y);
} …. // more code is needed

56

56

28
2020-09-30

The this Reference - so far


• Usage:
▪ In constructor,
o Reference to context object, can resolve ambiguity between
instance variables and parameters in constructor this.x = x;
o to call another constructor this(2,4);

▪ In instance method,
o Reference to context object, can resolve ambiguity between
instance variables and parameters in constructor this.x = x;
o to call another method from same class. this.move();
o to return current object to caller return this;
o to pass the current object as a parameter to another method
method(this);

57

57

Lab1, both usage

58

58

29
2020-09-30

Encapsulation
• we can add features to Point2D to make it easier to use
▪ we can add access modifiers to fields to prevent unauthorized
access or manipulation of data (information hiding)

▪ we can add constructors that set the values of the fields of a


Point2D object when it is created

▪ we can (need to) add methods that use the fields of Point2D to
perform some sort of computation
o e.g., provide access to the values of the fields
o e.g., calculate distance between two points, or distance to origin
o e.g., translate, rotate or scale a point (w.r.t. an origin)

▪ we are obliged to define certain standard methods like


toStrings(), equals() so that we can display, test and compare
objects in a meaningful way
59

59

Recall:
Organization of a Typical Java Program

package 2030.lab0;
• one or more files
import java.util;
• zero or one package
import java.util; name
• zero or more import
Class Student {
statements
int age; • one class
public student()
• zero or more fields
{…} (attributes)
public int getAge() • zero or more constructors
} {…}
• zero or more methods

60

60

30
2020-09-30

Methods

Basics
Accessors and Mutators
Anonymous objects
Object aliasing and pass-by-value

61

61

Methods
• a method performs some sort of computation
• a method is reusable
▪ anyone who has access to the method can use the method without
copying the contents of the method
▪ anyone who has access to the method can use the method without
knowing the contents of the method

• in Java, every method must be defined inside of a class


• define the behavior of object
• a method implementation consists of:
▪ the method header public static void doSth(…)
▪ a method body {……}
• a method may have an access and/or static modifier
• a method may/may not have a parameter list
• a method always has a return type declared
62
▪ void if not returning anything

62

31
2020-09-30

Method header

• the first line of a method declaration is sometimes called the


method header

public static boolean doSomething(int var1, int var2, … , int var3)

modifiers return type name parameter list

public void doSomething ( )

modifiers return type name parameter list

63

63

Method parameter list

• Imagine a method that computes distance of a point to another


point (x,y)

• the parameter list is the list of types and names that appear
inside of the parentheses

public double distanceTo(int x, int y)

parameter list

• the names in the parameter list must be unique


▪ i.e., duplicate parameter names are not allowed
▪ public double distanceTo(int y, int y);

64

64

32
2020-09-30

Methods with parameters

• if a method has parameters, then you can use the


parameter names as variables inside your method
▪ you cannot create new variables inside the method that
have the same name as a parameter
public double distanceTo(int x, int y){
int x = …;
};

▪ you cannot use the parameters outside of the method


o we say that the scope of the parameters is the method body

• you may create additional variables inside your method if


you wish
65

65

Method signature

• every method has a signature


▪ the signature consists of the method name and the types in
the parameter list
public double distanceTo(int x, int y)

has the following signature

name number and types of parameters

distanceTo (int, int )

signature

66

66

33
2020-09-30

Method signature

• other examples from java.lang.String


▪ headers
o public String toUpperCase()
o public char charAt(int index)
o public int indexOf(String str, int fromIndex)
o public void getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
▪ signatures
o toUpperCase()
o charAt(int)
o indexOf(String, int)
o getChars(int, int, char[], int)

67

67

Method signature

• method signatures in a class must be unique


• we can introduce a second method in the same class:

public double distanceTo() // dist to origin


public double distanceTo(double x, double y) // dist to x,y

• but not this one:

public double distanceTo(double r, double theta) why

or
public int distanceTo(double r, double theta)

68

68

34
2020-09-30

Different return types

69

69

Method signature
two or more methods with the same name but different
signatures are said to be overloaded

public double distanceTo(float x, float y)

public double distanceTo(double x, double y)

public double distanceTo(Point2 p) Different signature


in same class

are all (valid) overloaded methods


override ?
// tries to double x Same signature in
different classes
public static void twice (int x)
public static void twice (MyInteger x)
70 public static void twice (int[] x)

70

35
2020-09-30

add(1,3,5,7)

add(3,7)

add(3,5,7)

71

Overloading, cleanliness and readability of code

int[] a = {7,3,5,6,8,9};
Arrays.sort(a);
72
char[] c={'b','c','d','x','a'};
Arrays.sort(c);

72

36
2020-09-30

Constructor overloading
public class Point2D {
public float x;
public float y;

public Point2D() {
this.x = -1.0f;
this.y = 0.0f; Three overloaded
} constructors.
Must have different
public Point2D(float x, float y) { parameter list
this.x = x;
this.y = y;
}

public Point2D(Point2D other) {


this.x = other.x;
this.y = other.y;
}
73

73

Method return types

• all Java methods return nothing (void) or a single type of


value (a primitive type or an object)
• our method

public double distanceTo(double x, double y)

has the return type double

74

74

37
2020-09-30

/**
* return the distance to coordinate x y.
*
* @param x, the x coordinate
* @param y the y coordinate
*/

public double distanceTo(double x, double y) {


double deltaX = this.x – x;
double deltaY = this.y – y;
double d = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
return d;
}

• x, y is used in method as local variables


• created more local variables deltaX deltaY
• this is needed here
• create a variable d to store the return value of the method
75

75

package eecs2030.lab0;
another example
public class Lab0 {

public static boolean isBetween(int min, int max, int value)


{
boolean result = true;
if (value <= min) {
result = false;
}
if (value >= max) {
result = false;
}
// else result = false;
return result;
}

}
we create a variable result to store the return value of the method
76

76

38
2020-09-30

Method return values

• a method stops running immediately if a return statement


is run
▪ this means that you are not allowed to have additional code
if a return statement is reached
▪ however, you can have multiple return statements

• For void method, the method stops running immediately if


reach the end of method
static void C () static void D ()
{ {
C_stetement1; D_statement1;
D(); D_statement2;
C_statement2; }
77
}

77

package eecs2030.lab0;

public class Lab0 {

public static boolean isBetween(int min, int max, int value)


{
if (value <= min) {
return false;
// code not allowed here
}
if (value >= max) {
return false;
// code not allowed here
}
return true;
// code not allowed here
}

} we don’t create a variable to store the return value – due to


the fact that multiple return is allowed
78

78

39
2020-09-30

package eecs2030.lab0;

public class Lab0 {

public static boolean isBetween(int min, int max, int value)


{
if (value <= min || value >= max) {
return false;
} No () needed
return true;
} Operator precedence
Relational before Logical
<= >= before && ||
}

Alternative implementations
79 • there are many ways to implement this particular method
79

package eecs2030.lab0;

public class Lab0 {

public static boolean isBetween(int min, int max, int value)


{
if (value > min && value < max) {
return true;
} No () needed
return false;
} Operator precedence
Relational before Logical
<= >= before && ||
}

Alternative implementations
80 • there are many ways to implement this particular method
80

40
2020-09-30

package eecs2030.lab0;

public class Lab0 {

public static boolean isBetween(int min, int max, int value)


{
boolean result = value > min && value < max;
return result;
} No () needed

} Operator precedence
Relational before Logical
<= >= before && ||
Assignment = is lower

Alternative implementations
81 • there are many ways to implement this particular method
81

package eecs2030.lab0;

public class Lab0 {

public static boolean isBetween(int min, int max, int value)


{
return value > min && value < max;
}
No () needed
}
Operator precedence
Relational before Logical
<= >= before && ||

Alternative implementations
82 • there are many ways to implement this particular method
82

41
2020-09-30

Methods

Basics
Accessors and Mutators
Anonymous objects
Object aliasing and pass-by-value

83

83

Accessor and Mutator Methods

• ACCESSOR METHODS (getter)


▪ a method that returns information about the state of an object
is called an accessor method
▪ for example, we can provide methods that return the x or y
coordinate of a point getX(), and getY()

• MUTATOR METHODS (setter)


▪ methods that change the state of an object are called
mutator methods
▪ setX(float), setY(float), set(float, float) are all
mutator methods
84

84

42
2020-09-30

ACCESSOR METHODS (getter)

/**
* Returns the x coordinate of this point.
*
* @return the x coordinate of this point
*/
public float getX() {
return this.x;
}

is ‘this’ a
must?

85

85

ACCESSOR METHODS (getter)

/**
* Returns the y coordinate of this point.
*
* @return the y coordinate of this point
*/
public float getY() {
return this.y;
}

is ‘this’ a
must?

86

86

43
2020-09-30

MUTATOR METHODS (setters)


/**
* Sets the x coordinate to the specified value.
*
* @param newX the new x coordinate
*/
public void setX(float newX) {
this.x = newX;
} is ‘this’ a
must?

/** p.setX(2.2f);
* Sets the y coordinate to the specified value.
*
* @param newY the new y coordinate
*/
public void setY(float y) { is ‘this’ a
must?
this.y = y;
87
} p.setY(4.5f);

87

Accessors and mutators


• adding a copy constructor allows the client to simplify
their code

public static void main(String[] args) {


// create a point
Point2D p = new Point2D(-1.0f, 1.5f);

// get its coordinates


System.out.println("p = (" + p.getX() + ", " + p.getY() + ")");

Point2D q = new Point2D(p);

q.setX(100.0f);
q.setY(200.0f);
System.out.println("q = (" + q.getX() + ", " + q.getY() + ")");

}88

88

44
2020-09-30

Generating getting setting in eclipse

89

89

90

90

45
2020-09-30

is ‘this’ a
must?

91

91

Calling getters and setters


Point2D p = new Point2D(3.0f, 6.2f);
float a = p.getX();
p.setY(7.0f);
System.out.println(p.getX());

return p.getY(); // valid? yes


p.getY(); // valid? Yes. But useless

System.out.println(p.setY(7.0f)); // valid?
float b = p.setY(7.0f); // valid?
return p.setY(7.0f); // valid?
p.setX(6.5f).setY(7.0f);
92 // valid?
92

46
2020-09-30

MUTATOR METHODS (setter) other version


/**
* Sets the x coordinate to the specified value.
*
* @param newX the new x coordinate
* @return a reference to this point
*/
public Point2D setX2(float newX) { Another use of ‘this’
this.x = newX;
return this;
} p = p.setX2(6.5f);
/**
* Sets the y coordinate to the specified value.
*
* @param newY the new y coordinate
* @return a reference to this point
p.setX(6.5f).setY(7.0f);
*/ p.setX(6.5f);
public Point2D setY2(float newY) { p.setY(7.0f);
this.y = newY; Allow a call chain in one line
93 return this; p.setX2(6.5f).setY2(7.0f);
}
93

More METHODS using this


/**
* move the x coordinate with the specified value.
*
* @param deltaX the moving amount
*
*/
public void moveX(float deltaX) {
this.x += deltaX; p.moveX(4.5);
} p.moveY(3.4);

/**
* move the x coordinate with the specified value.
*
* @param deltaX the moving amount
* @return a reference to this point
*/
public Point2D moveX2(float deltaX) {
this.x += deltaX;
return this; Allow a call chain in one line
94
} p.moveX2(4.5).moveY2(3.4);
94

47
2020-09-30

The this Reference - so far


• Usage:
▪ In constructor,
o Reference to context object, can resolve ambiguity between
instance variables and parameters in constructor this.x = x;
o to call another constructor this(2,4);

▪ In instance method,
o Reference to context object, can resolve ambiguity between
instance variables and parameters in constructor this.x = x;
o to call another method from same class. this.move();
o to return current object to caller return this;
o to pass the current object as a parameter to another method
method(this);

95

95

Class Diagram
UML Point2D
- x : int
• Public members are - y : int
shown by + + Point()
• Private members are + Point(int, int)
shown by - + getX(): int
• Protected members are + getX(): int
shown by # + setX(int): void
• Package members are + setY(int): void
shown by ~ + moveX(int): void
+ equals(Object) : Boolean
+ hashCode() : int
+ toString() : String
...

(Unified Modeling Language) is a standard language for


specifying, visualizing, constructing, and documenting the
96
artifacts of software systems

96

48
2020-09-30

Summary and future work

• This week
▪ Classes
o basics
o encapsulation
o fields
o constructors
o methods

• Plan for next few lectures:


▪ static features
▪ Obligatory methods
o toString()
▪ Exception and Junit
97

97

49

You might also like