Java Method Invocation and Access Patterns
Java Method Invocation and Access Patterns
• Example:
1
Note
• If a method is invoked from within another
method of the same object dotted notation
is not mandatory
class Book {
int pages;
void readPage(int n) { … }
void readAll() {
for(int i=0; i<pages; i++){
readPage(i);
}
}
}
2
Note (contʼd)
• In such cases this is implied
• It is not mandatory
class Book {
int pages;
void readPage(int n){…}
void readAll() {
for(…){ equivalent
readPage(i);
} }
} void readAll() {
for(…){
[Link](i);
} }
3
Access to attributes
• Dotted notation
[Link]
• A reference is used like a normal variable
4
Access to attributes
• Methods accessing attributes of the same
object do not need to use the object
reference
class Car {
String color;
…
void paint(){
color = “green”;
// color refers to current obj
}
}
5
Using “this” for attributes
• The use of this is not mandatory
• It can be useful in methods to disambiguate
object attributes from local variables
class Car{
String color;
...
void paint (String color) {
[Link] = color;
}
}
6
Chaining dotted notations
• Dotted notations can be combined in a
single expression
[Link](“Hello world!”);
7
Method Chaining
public class Counter {
private int value;
public Counter reset(){
value=0; return this;
}
public Counter increment(int by){
[Link]+=by; return this;
}
public Counter print(){
[Link](value);
return this;
} Counter cnt = new Counter();
} [Link]().print()
.increment(10).print()
.decrement(7).print();
Operations on references
• Only the comparison operators == and !=
are defined
• Note well: the equality condition is evaluated on
the values of the references and NOT on the
objects themselves!
• The relational operators tells whether the
references points to the same object in memory
• Dotted notation is applicable to object
references
• There is NO pointer arithmetic
9
Overloading
• Several methods in a class can share the same name
• They must have have distinct signature
• A signature consists of:
• Method name
• Ordered list of argument types
10
Overloading: disambiguation
• Invocation of an overloaded method is potentially ambiguous
• Disambiguation is performed by the compiler based on actual
parameters
• The method definition whose argument types list matches the actual
parameters, is selected
Overloading
class Car {
String color;
void paint(){
color = "white";
}
void paint(int i){ … }
void paint(String newCol){
color = newCol;
}
}
Constructors with overloading
class Car { // …
// Default constructor, creates a red Ferrari
public Car(){
color = "red";
brand = "Ferrari";
}
// Constructor accepting the brand only
public Car(String carBrand){
color = "white”;
brand = carBrand;
}
// Constructor accepting the brand and the color
public Car(String carBrand, String carColor){
color = carColor;
brand = carBrand;
}
}
14
Destruction of objects
• Memory release, in Java, is no longer a
programmer’s concern
• Managed memory language
• Before the object is really destroyed the
method finalize, if defined, is invoked:
public void finalize()
15
Scope and encapsulation
Scope and Syntax
• Visibility modifiers
• Applicable to members of a class
• private
• Member is visible and accessible from instances
of the same class only
• public
• Member is visible and accessible from
everywhere
17
Info hiding
class Car {
public String color;
Car a = new Car();
}
[Link]="white"; // ok
class Car {
private String color;
public void paint(String color)
{[Link] = color;}
better }
Car a = new Car();
[Link] = "white"; // error
[Link]("green"); // ok
18
Info hiding
class Car{
private String color;
public void paint(); no
}
class B {
public void f1(){
yes ...
};
}
19
Access
Private
(attribute / yes no
method)
Public
(attribute / yes yes
method)
20
Getters and setters
• Methods used to read/write a private
attribute
• Allow to better control in a single point each
write access to a private field
public String getColor() {
return color;
}
public void setColor(String newColor) {
color = newColor;
}
21
Example without getter/setter
public class Student {
public String first;
public String last;
public int id;
public Student(…){…}
}
[Link](s);
// prints its values and asks students to
// print their data
[Link]();
}
}
24
Example with getter/setter
public class Student {
private String first;
private String last;
private int id;
public String toString() {
return first + " " +
last + " " +
id;
}
}
25
Example with getter/setter
public class Exam {
private int grade;
private Student student;
public void print() {
[Link](“Student ” +
[Link]() + “got ” + grade);
}
public void setStudent(Student s) {
[Link] =s;
}
}
26
Getters & setters vs. public fields
• Getter
• Allow changing the internal representation without affecting
• E.g. can perform type conversion
• Setter
• Allow performing checks before modifying the attribute
• E.g. Validity of values, authorization
Modifier / Query methods
• Modifiers
• Change the state of the object but do not return a value
• e.g. setters
• Query
• Return a result and do not change the state of the object
• No side-effects
• e.g. getters
Modifier / Query Separation
• Invocations to
• queries can be added, removed, and swapped without affecting the
overall behavior
• modifiers cannot be touched without affecting the behavior
• Important to clearly separate them:
• Queries return a value
• Modifiers return void
See: [Link]
Original concepts in: [Link], Object-Oriented Software Construction, Prentice-Hall, 1997
Package
• Class is a better mechanism of
modularization than a procedure
• But it is still small, when compared to the
size of an application
• For the purpose of code organization and
structuring Java provides the package
feature
30
Package
• A package is a logic set of class definitions
• These classes consist in several files, all
stored in the same folder
• Each package defines a new scope (i.e., it
puts bounds to visibility of names)
• It is therefore possible to use same class
names in different package without name-
conflicts
31
Package name
• A package is identified by a name with a
hierarchic structure (fully qualified name)
• E.g. [Link] (String, System, …)
32
Examples
• [Link]
• Window
• Button
• Menu
• [Link] (sub-package)
• MouseEvent
• KeyEvent
33
Creation and usage
• Declaration:
• Package statement at the beginning of each
class file
package packageName;
• Usage:
• Import statement at the beginning of class file
(where needed)
import [Link]; Import single class
(class name is in
scope)
import [Link].*;
Import all classes
but not the sub
packages
34
Access to a class in a package
• Referring to a method/class of a package
int i = [Link]()
35
Default package
• When no package is specified, the class belongs to the
default package
• The default package has no name
• Classes in the default package cannot be accessed by
classes residing in other packages
• Usage of default package is a bad practice and is
discouraged
Package and scope
37
Package visibility
Package P
class A {
public int a1; class B {
38
Visibility w/ multiple packages
• public class A { }
• Class and public members of A are visible from
outside the package
• class B { }
Package visibility
• Class and any members of B are not visible from
outside the package
• private class A { }
• Illegal: why?
class A { class B {
public int a1; public int a3;
private int a2; private int a4;
public void f1(){} }
}
no no
Package Q
class C {
public void f2(){}
}
40
Multiple packages
Package P
yes no
Package Q
class C {
public void f2(){}
}
41
Access rules
Method of other Method of other
Method of the
class in the same class in other
same class
package package
42
Wrapper Classes
String
• No primitive type to represent string
• String literal is a quoted text
•C
• char s[] = “literal”
• Equivalence between strings and char arrays
• Java
• char[] != String
• String class in [Link] package
45
Wrapper Classes
Defined in [Link] package
Primitive type Wrapper Class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
void Void
46
Conversions
[Link]()
Integer wi
[Link]() [Link](s)
new Integer(s)
new Integer(i)
[Link](i)
int i String s
[Link](s)
[Link](i)
""+i
47
Example
Integer obj = new Integer(88);
String s = [Link]();
int i = [Link]();
int j = [Link]("99");
int k=(new Integer(99)).intValue();
48
Using Scanner
• Scanner can be initialized with a string
Scanner s = new Scanner("123");
• then values can be parsed
int i = [Link]();
• In addition a scanner is able to parse several numbers in the same
string
Autoboxing
51
Arrays
Array
• An array is an ordered sequence of variables
of the same type which are accessed
through an index
• Can contain both primitive types or object
references (but no object values)
• Array dimension can be defined at run-time,
during object creation (cannot change
afterwards)
53
Array declaration
• An array reference can be declared with one
of these equivalent syntaxes
int[] a;
int a[];
• In Java an array is an Object and it is stored
in the heap
• Array declaration allocates memory space
for a reference, whose default value is null
a null
54
Array creation
• Using the new operator…
int[] a;
a = new int[10];
String[] s = new String[5];
55
Example - primitive types
a heap
int[] a; null
a heap
a = new int[6]; 0
0
0
0
0
0
primes heap
int[] primes = 2
3
{2,3,5,7,11,13}; 5
7
11
13
56
Example - object references
s heap
String[] s = new null
String[6]; null
null
null
null
null
s heap
s[1] = new null
String(“abcd”); null
“abcd”
null
null
null
Person[] p =
heap
{new Person(“John”) , p
John
new Person(“Susan”)}; Susan
57
Operations on arrays
• Elements are selected with brackets [ ] (C-
like)
• But Java makes bounds checking
58
Operations on arrays
• An array reference is not a pointer to the
first element of the array
• It is a pointer to the array object
59
For each
• New loop construct:
for( Type var : set_expression )
• Very compact notation
• set_expression can be
• either an array
• a class implementing Iterable
• The compiler can generate automatically the loop
with correct indexes
• Less error prone
60
For each - example
• Example:
for(String arg : args){
//...
}
• is equivalent to
for(int i=0; i<[Link];++i){
String arg= args[i];
//...
}
61
Multidimensional array
• Implemented as array of arrays
heap table[0][2]
table
null
null null
null “Mary”
null
table[0]
62
Rows and columns
• Since rows are not stored in adjacent
positions in memory they can be easily
exchanged
63
Rows with different length
• A matrix (bidimensional array) is
indeed an array of arrays
int[][] triangle = new int[3][]
triangle
null
null
null
heap
for (int i=0; i< [Link]; i++)
triangle[i] = new int[i+1];
triangle
0
0
0 0
0
0
64
Static Attributes and
Methods
Static attributes
• Represent properties which are common to all instances
of a class
• A single copy of a static attribute is shared by all instances of
the class
• Sometimes called class attributes as opposed to instance
attributes
• Static attributes exists before any object is created
• A change performed by any object is visible to all instances at
once
• They are defined with the static modifier
68
Static attributes: why
• Used to keep a shared property
• A count of created instances
• A pool of all instances
• Keep a common constant value
class Car {
static int countBuiltCars = 0;
public Car(){
countBuiltCars++;
}
}
69
Static methods
• Static methods are not related to any
instance
• They are defined with the static modifier
• Used to implement functions
public class HelloWorld {
public static void main (String args[]) {
[Link]("Hello World!");
}
}
public class Utility {
public static int inverse(double n){
return 1 / n;
}
}
70
Static members access
• The name of the class is used to access the member:
[Link]
[Link](10);
• It is possible to import all static items:
import static [Link].*;
• Then all static members are accessible without specifying the
class name
• Note: Impossible if class in default package
Static methods: why
• Implement functions
• Avoid creating an object just to invoke the method (see e.g., main())
• Collected in utility classes
• Provide ideal factory method
• Method to create an instance
Function method
• A “function” is a method whose return value depends only on the
arguments
• Typically defined as static
• Often collected within a utility class
• Class containing static function methods only
• Wrapper types include several function methods for conversion
purposes
Utility classes
• System
• Interact with the operating system
• Math
• Mathematical functions
• Arrays
• Functions to operate on arrays
• Objects
• Functions to operate on object
Class Math
• Defines several math-related function methods
• Trigonometric functions
• Min-max
• Exponential and logarithms
• Truncations
• Random number generation
Class Arrays
• Arrays utility functions
• Binary search (binarySearch())
• Copy (copyOf(), copyOfRange())
• Equality (equals(), deepEquals())
• Fill-in (fill())
• Sorting (sort())
• String representation (toString())
Class System
• General purpose utilities
• static long currentTimeMillis()
• Current system time in milliseconds
• static void exit(int code)
• Terminates the execution of the JVM
• static final PrintStream out
• Standard output stream,
• Also err for standard error
Factory method
• A method used to create an object
• Encapsulates an explicit object creation with the new operator
• Can be used to:
• Return objects from a pool
• Requires immutable objects
• Either pre-allocated or cached
• Simplify creation
• Maintain a collection of created objects
• Control new objects allocation
• See e.g., Singleton pattern
Factory methods: Integer
• valueOf(int)
• Replaces new Integer(int)
• Cache values in the range -128 to 127
• valueOf(String)
• Returns the integer corresponding to the parsed string
• Same as:
new Integer([Link](s))
Final Attributes
• An attribute declared as final:
• cannot be changed after object construction
• can be initialized inline or by the constructor
class Student {
final int years=3;
final String id;
public Student(String id){
[Link] = id;
}
}
Final variables / parameters
• Final parameters cannot be changed
• Non final parameters are treated as local variables (initialized by the
caller)
• Final variables
• Cannot be modified after initialization
• Initialization can occur at declaration or later
Constants
• Use final static modifiers
• final implies not modifiable
• static implies non redundant
final static float PI = 3.14;
…
PI = 16.0; // ERROR, no changes
final static int SIZE; // missing init
82
Static initialization block
• Block of code preceded by static
• Executed at class loading time
• Context:
• A class represents a concept that requires a single instance
• Problem:
• Clients could use this class in an inappropriate way
private Singleton() { }
private static Singleton instance;
public static Singleton getInstance(){
if(instance==null)
instance = new Singleton();
return instance;
}
87
Fluent Interfaces
• Method to design OO API based on extensive use of method
chaining
• The goal is to improve readability
• Code looks like prose
• Often used to build complex objects
• Create a sort of Domain Specific Language (DSL) leveraging the
syntax of the host language
See: [Link]
P [W] = ⋅ V[V]
T[h]
⎯⎯⎯⎯ ⎯⎯⎯⎯
u(P ) = P ∗ (u(C)/C + u(T)/T + u(V)/V)
Example
10.40 kg ⋅ m2 ⋅ s−3
• Usual non-fluent
Measure power = new Measure(10.4);
[Link]("kg", 1);
[Link]("m", 2);
[Link]("s", -3);
[Link](2);
• Fluent
Measure power = [Link](10.4).
is("kg").by("m").squared().by("s").to(-3).
withPrecision(2).done();
Measure
public class Measure {
private double value;
private Unit unit;
private int precision;
public Measure(double value) {
[Link] = value;
}
public void setPrecision(int precision) {
[Link] = precision;
}
public void addUnit(String name, double exp){
unit = new Unit(name,exp,unit);
}
}
public static
Builder value(double v){
Fluent Builder }
return new Builder(v);
94
Variable arguments- example
static int min(int... values){
int res = Integer.MAX_VALUE;
for(int v : values){
if(v < res) res=v;
}
return res;
}
public static void main(String[] args) {
int m = min(9,3,5,7,2,8);
[Link]("min=” + m);
}
95
Enum
• Defines an enumerative type
public enum Suits {
SPADES, HEARTS, DIAMONDS, CLUBS
}
• Variables of enum types can assume only one of the enumerated
values
Suits card = [Link];
• They allow much stricter static checking compared to integer constants
(e.g. in C)
96
Enum
• Enum can are similar to a class that automatically instantiates
the values
class Suits {
public static final Suits HEARTS=
new Suits
(“HEARTS”,0);
public static final Suits DIAMONDS=
new
Suits(“DIAMONDS”,1);
public static final Suits CLUBS=
new Suits (“CLUBS”,
2);
public static final Suits SPADES=
new Suits (“SPADES”,
3);
private Suits (String enumName, int index) {…}
}
97
Nested Classes
Nested class types
• Static nested class
• Within the container name space
• Inner class
• As above + contains a link to the creator container object
• Local inner class
• As above + may access (final) local variables
• Anonymous inner class
• As above + no explicit name
(Static) Nested class
• A class declared inside another class
package pkg;
class Outer {
static class Nested {
}
}
• Similar to regular classes
• Subject to usual member visibility rules
• Fully qualified name includes the outer class:
• [Link]
(Static) Nested class - Usage
• Static nested classes can be used to hide classes that are used
only within another class
• Reduce namespace pollution
• Encapsulate internal details
• Nested class lies within the scope of the outer class
(Static) Nested class - Example
public class StackOfInt{
private static class Element {
int value;
Element next;
}
private Element head
public void push(int v){ … }
public int void pop(){ … }
}
Inner Class
• Linked to an instance
• A.k.a. non-static nested class
package pkg;
class Outer {
class Inner{
}
}
X x = new X();
[Link]([Link]());
}
• References to local variables are allowed
• Replaced with “current” value
• Set of such local variables is called closure
Local Inner Class
• Declared inside a method
public void m(){
int j=1; 1
class X {
int plus(){ return j + 1; } result should
What
} we expect?
j++;
X x = new X();
[Link]([Link]());
}
• Local variable cannot be changed after being referred to by an
inner class
Local Inner Class
• Declared inside a method
public void m(){
final int j=1;
class X {
int plus(){ return j + 1; }
}
j++;
X x = new X();
[Link]([Link]());
}
• Local variables used in local inner classes should
be declared final
• Or be effectively final
Anonymous Inner Class
• Local class without a name
• Only possible with inheritance
• Implement an interface, or
• Extend a class
• See: inheritance