0% found this document useful (0 votes)
11 views

J02 JavaBasics Part III-2

Uploaded by

yesshakez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

J02 JavaBasics Part III-2

Uploaded by

yesshakez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

Method invocation

• A method is invoked using dotted notation


objectReference.method(parameters)

• Example:

Car a = new Car();


a.turnOn();
a.paint("Blue");

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(…){
this.readPage(i);
} }
3
Access to attributes
• Dotted notation
objectReference.attribute
• A reference is used like a normal variable

Car a = new Car();


a.color = "Blue"; //what’s wrong here?
boolean x = a.turnedOn;

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) {
this.color = color;
}
}
6
Chaining dotted notations
• Dotted notations can be combined in a
single expression

System.out.println(“Hello world!”);

• System is a Class in package java.lang


• out is a (static) attribute of System referencing
an object of type PrintStream (representing the
standard output)
• println() is a method of PrintStream which
prints a text line followed by a new-line

7
Method Chaining
public class Counter {
private int value;
public Counter reset(){
value=0; return this;
}
public Counter increment(int by){
this.value+=by; return this;
}
public Counter print(){
System.out.println(value);
return this;
} Counter cnt = new Counter();
} cnt.reset().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();
}
a.color="white"; // ok

class Car {
private String color;
public void paint(String color)
{this.color = color;}
better }
Car a = new Car();
a.color = "white"; // error
a.paint("green"); // ok
18
Info hiding
class Car{
private String color;
public void paint(); no
}

class B {
public void f1(){
yes ...
};
}

19
Access

Method in the Method in


same class another class

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(…){…}
}

public class Exam {


public int grade;
public Student student;
public Exam(…){…}
}
22
Example without getter/setter
class StudentExample {
public static void main(String[] args) {
// defines a student and her exams
// lists all studentʼs exams
Student s=new Student(“Alice",“Green",1234);
Exam e = new Exam(30);
e.student = s;
// print vote
System.out.println(e.grade);
// print student
System.out.println(e.student.last);
}
}
23
Example with getter/setter
class StudentExample {
public static void main(String[] args) {
Student s = new Student(“Alice”, “Green”,
1234);
Exam e = new Exam(30);

e.setStudent(s);
// prints its values and asks students to
// print their data
e.print();
}
}

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() {
System.out.println(“Student ” +
student.toString() + “got ” + grade);
}
public void setStudent(Student s) {
this.student =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: https://www.martinfowler.com/bliki/CommandQuerySeparation.html
Original concepts in: B.Meyer, 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. java.lang (String, System, …)

• Conventions to create unique names


• Internet name in reverse order
• it.polito.myPackage

32
Examples
• java.awt
• Window
• Button
• Menu

• java.awt.event (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 packageName.className; Import single class
(class name is in
scope)
import java.awt.*;
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 = myPackage.Console.readInt()

• If two packages define a class with the same


name, they cannot be both imported
• If you need both classes you have to use
one of them with its fully-qualified name:
import java.sql.Date;
Date d1; // java.sql.Date
java.util.Date d2 = new java.util.Date();

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

• Scope rules also apply to packages


• The “interface” of a package is the set of public
classes contained in the package
• Hints
• Consider a package as an entity of modularization
• Minimize the number of classes, attributes, methods
visible outside the package

37
Package visibility

Package P

class A {
public int a1; class B {

private int a2; yes public int a3;

public void f1(){} private int


no a4;
}
}

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?

The class and its members would be visible to


themselves only
39
Multiple packages
Package P

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

public class A { class B {


public int a1; public int a3;
private int a2; private int a4;
public void f1(){} }
}

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

Private member Yes No No

Package member Yes Yes No

Public member in Yes Yes No


package class

Public member in Yes Yes Yes


public class

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 java.lang package

See slide deck “Java Characters and Strings”


44
Motivation
• In an ideal OO world, there are only classes
and objects
• For the sake of efficiency, Java use primitive
types (int, float, etc.)

• Wrapper classes are object versions of the


primitive types
• They define conversion operations between
different types

45
Wrapper Classes
Defined in java.lang 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
wi.intValue()
Integer wi

wi.toString() Integer.valueOf(s)
new Integer(s)
new Integer(i)
Integer.valueof(i)

int i String s

Integer.parseInt(s)

String.valueOf(i)
""+i

47
Example
Integer obj = new Integer(88);
String s = obj.toString();
int i = obj.intValue();

int j = Integer.parseInt("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 = s.nextInt();
• In addition a scanner is able to parse several numbers in the same
string
Autoboxing

• Since Java 5, the conversion between primitive types and


wrapper classes is performed automatically (autoboxing)
Integer i= new Integer(2); int j;
j = i + 5;
//instead of:
j = i.intValue()+5;
i = j + 2;
//instead of:
i = new Integer(j+2);
50
Character
• Utility methods on the kind of char
• isLetter(), isDigit(), isSpaceChar()
• Utility methods for conversions
• toUpper(), toLower()

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];

• …or using static initialization,


filling the array with values
int[] primes = {2,3,5,7,11,13};
Person[] p = { new Person(“John”),
new Person(“Susan”) };

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

• Array length (number of elements) is given


by attribute length

for (int i=0; i < a.length; i++)


a[i] = i;

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

• Arithmetic on pointers does


not exist in Java

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<args.length;++i){
String arg= args[i];
//...
}

61
Multidimensional array
• Implemented as array of arrays

Person[][] table = new Person[2][3];


table[0][2] = new Person(“Mary”);

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

double[][] balance = new double[5][6];


...
double[] temp = balance[i];
balance[i] = balance[j];
balance[j] = temp;

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< triangle.length; 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[]) {
System.out.println("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:
Car.countCountBuiltCars
Utility.inverse(10);
• It is possible to import all static items:
import static package.Utility.*;
• 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(Integer.parseInt(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){
this.id = 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

• All uppercase (coding conventions)

82
Static initialization block
• Block of code preceded by static
• Executed at class loading time

public final static double 2PI;


static {
2PI = Math.acos(-1);
}
Example: Global directory (a)
• Manages a global name directory
class Directory {
public final static Directory root;
static {
root = new Directory();
}
// …
}
What if not always useful and
expensive creation?
Example: Global directory (b)
• Manages a global directory
class Directory {
private static Directory root;
public static Directory getInstance(){
if(root==null){
root = new Directory();
}
return root;
}
Created on-demand at first
// … usage
}
Singleton Pattern

• Context:
• A class represents a concept that requires a single instance
• Problem:
• Clients could use this class in an inappropriate way

See slide deck on design patterns


86
Singleton Pattern
Singleton class
Singleton
-Singleton()
+getInstance(): Singleton
singletonOperation()
Factory method

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: https://www.martinfowler.com/bliki/FluentInterface.html
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);
power.addUnit("kg", 1);
power.addUnit("m", 2);
power.addUnit("s", -3);
power.setPrecision(2);
• Fluent
Measure power = Measure.value(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) {
this.value = value;
}
public void setPrecision(int precision) {
this.precision = 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);

public static class Builder{


private Measure object;
private String unitName;
public Builder(double v){object = new Measure(v);}
public Builder is(String name) {
unitName = name; return this;
}
public Builder by(String name) {
if(unitName!=null) {
object.addUnit(unitName, 1);
}
unitName = name; return this;
Fluent Builder
public Builder squared() {
object.addUnit(unitName, 2);
unitName = null; return this;
}
public Builder to(double exponent) {
object.addUnit(unitName, exponent);
unitName = null; return this;
}
public Measure done() { return object; }
public Builder withPrecision(int precision) {
object.setPrecision(precision);
return this;
}
}
Other Features
Variable arguments
• It is possible to pass a variable number of
arguments to a method using the varargs
notation
method( type ... args )
• The compiler assembles an array that can be
used to scan the actual arguments
• Type can be primitive or class

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);
System.out.println("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 = Suits.HEARTS;
• 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:
• pkg.Outer.Inner
(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{
}
}

• It is linked to instances of enclosing outer classes (i.e. it is non


static)
Inner Class

• Any inner class instance is associated with the instance of its


enclosing class that instantiated it
• Cannot be instantiated from
• a static method
• Other classes
• Has direct access to that enclosing object methods and fields
Inner Class (example)
public class Counter {
int i;
public class Incrementer {
private int step=1;
public void doIncrement(){ i+=step; }
Incrementer(int step){ this.step=step; }
}
public Incrementer buildIncrementer(int step){
inner instance is linked to this
return new Incrementer(step);
outer object
}
public int getValue(){
return i; Counter c = new Counter()
} Incrementer byOne = c.buildIncrementer(1);
} Incrementer byFour = c.buildIncrementer(4);
byOne.doIncrement();
byFour.doIncrement();
c.getValue(); // -> 5
Local Inner Class
• Declared inside a method
public void m(){
int j=1;
class X { 1
int plus(){ return j + 1; }
}

X x = new X();
System.out.println(x.plus());
}
• 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();
System.out.println(x.plus());
}
• 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();
System.out.println(x.plus());
}
• 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

You might also like