puzzle 1 what does the following program print? public class puzzle01 { public static void...
TRANSCRIPT
Puzzle 1 what does the following program print?
public class Puzzle01
{
public static void main(String[] args)
{
System.out.print("C" + "S" + "E");
System.out.println('1' + '0' + '3' + '0' + 'z');
}
}
1
Solution
2
the program prints CSE318 instead of CSE1030Z
the problem occurs because the operator + is defined only for Strings and primitive numeric types the + operator concatenates Strings if and only if
at least one of the arguments is a String char is a primitive numeric type
Utilities
Implementing static features
3
Goals for Today initiate the design of simple class learn about class attributes
public static final
learn about preventing class instantiation
4
Motivation
5
you want to produce a software product that is to be used in many different countries
many different systems of measurement; for example distance
metre/kilometre versus yard/mile volume
teaspoon/tablespoon/cup versus millilitre/litre force
newton versus pound-force currency
CAN dollar versus US dollar versus euro versus …
Errors in Converting Units
6
errors in converting units can have catastrophic consequences NASA Mars Climate Orbiter
destroyed by navigation error caused by one subcontractor using Imperial units (pound-force) instead of metric (newton)
drug over/underdosing “Tenfold errors in pediatric doses are not uncommon. ”
Pediatric medication errors: predicting and preventing tenfold disasters. Journal of Clinical Pharmacology, 34(11):1043-5, 1994.
Review: Java Class
7
a class is a model of a thing or concept
in Java, a class is the blueprint for creating objects attributes
the structure of an object; its components and the information (data) contained by the object
methods the behaviour of an object; what an object can do
Designing a Class
8
to decide what attributes and methods a class must provide, you need to understand the problem you are trying to solve the attributes and methods you provide (the
abstraction you provide) depends entirely on the requirements of the problem
Person
appearancevoice
…
draw()talk()
…
Person
agephotograph
…
compatibleWith(Person)
contact ()…
video game person dating service person
class name
attributes
methods
Designing a Class to Convert Distances
9
design a class to convert between kilometres and miles
what attributes are needed? number of kilometres per mile
note: the number of kilometres in a mile never changes; it is genuinely a constant value
attributes that are constant have all uppercase names
DistanceUtility
KILOMETRES_PER_MILE : double attribute type
Version 1
10
public class DistanceUtility
{
// attributes
public static final
double KILOMETRES_PER_MILE = 0.621371192;
}
lay out of a typical class : see [AJ 4.1], [notes 1.2]
Attributes
11
an attribute is a member that holds data a constant attribute is usually declared by
specifying1. modifiers
1. access modifier public
2. static modifier static
3. final modifier final
2. type double
3. name KILOMETRES_PER_MILE
4. value 0.621371192
public static final double KILOMETRES_PER_MILE = 0.621371192;
Attributes
12
attribute names must be unique in a class the scope of an attribute is the entire class [JBA] and [notes] call public attributes fields
public Attributes
13
a public attribute is visible to all clients
public attributes break encapsulation a NothingToHide object has no control over the
value o f x clients can put a NothingToHide object into an
invalid state
public class NothingToHide { public int x; // always positive}
// client of NothingToHideNothingToHide h = new NothingToHide();h.x = 100;
h.x = -500; // x not positive
public Attributes
14
a public attribute makes a class brittle in the face of change
public attributes are hard to change they are part of the class API changing access or type will break exisiting client
code
public class NothingToHide { private int x; // always positive}
// existing client of NothingToHideNothingToHide h = new NothingToHide();h.x = 100; // no longer compiles
public Attributes
15
Avoid public attributes in production code except when you want to expose constant value types
static Attributes
16
an attribute that is static is a per-class member only one copy of the attribute, and the attribute is
associated with the class every object created from a class declaring a static
attribute shares the same copy of the attribute textbook uses the term static variable [AJ 256] also commonly called class variable
static Attributes
17
DistanceUtility u =
new DistanceUtility();
DistanceUtility v =
new DistanceUtility();
64 client invocation
u
see [JBA 4.3.3] for another example
500 DistanceUtility class
KILOMETRES_PER_MILE 0.621371192
1000 DistanceUtility object
???
1100 DistanceUtility object
???
v1000
1100
belongs to class
no copy ofKILOMETRES_PER_MILE
static Attribute Client Access
18
a client can access a public static attribute without requiring an object use the class name followed by a period followed
by the attribute name
it is legal, but considered bad form, to access a public static attribute using an object
// client of DistanceUtilitydouble kmPerMi = Distance.KILOMETRES_PER_MILE;
// client of DistanceUtility; avoid doing thisDistanceUtility u = new DistanceUtility();double kmPerMi = u.KILOMETRES_PER_MILE;
final Attributes
19
an attribute (or variable) that is final can only be assigned to once public static final attributes are typically
assigned when they are declared
public static final double
KILOMETRES_PER_MILE = 0.621371192;
public static final attributes are intended to be constant values that are a meaningful part of the abstraction provided by the class
final Attributes of Primitive Types
20
final attributes of primitive types are constantpublic class AlsoNothingToHide { public static final int x = 100;}
// client of AlsoNothingToHideAlsoNothingToHide.x = 88; // will not compile;
// attribute is final and// previously assigned
final Attributes of Immutable Types
21
final attributes of immutable types are constant
also, String is immutable it has no methods to change its contents
public class StillNothingToHide { public static final String x = "peek-a-boo";}
// client of StillNothingToHideStillNothingToHide.x = "i-see-you"; // will not compile;
// attribute is final and// previously assigned
final Attributes of Mutable Types
22
final attributes of mutable types are not logically constant; their state can be changed
public class ReallyNothingToHide { public static final int[] x = { 0, 1, 2 };}
// client of ReallyNothingToHideint[] y = { 100, 101, 102, 103 };ReallyNothingToHide.x = y; // will not compile;
// attribute is final and// previously assigned
ReallyNothingToHide.x[1] = 10000;// works!
final Attributes of Mutable Types
23
ReallyNothingToHide class
final x 192 700
:
700 int[] obj
:
not final 0
not final 1
not final 2
ReallyNothingToHide.x[1] = 10000;
10000
final Attributes of Mutable Types
24
final attributes of mutable types are not logically constant; their state can be changed
public class LastNothingToHide { public static final ArrayList<Integer> x =
new ArrayList<Integer>();}
// client of LastNothingToHideArrayList<Integer> y = new ArrayList<Integer>();LastNothingToHide.x = y; // will not compile;
// attribute is final and// previously assigned
LastNothingToHide.x.add( 10000 );// works!
final Attributes
25
Avoid using mutable types as public constants.
new DistanceUtility Objects
26
our DistanceUtility API does not expose a constructor but
DistanceUtility u = new DistanceUtility();
is legal
if you do not define any constructors, Java will generate a default no-argument constructor for you
our DistanceUtility API exposes only static constants (and methods later on) its state is constant
there is no benefit in instantiating a DistanceUtility object a client can access the constants (and methods)
without creating a DistanceUtility object
double kmPerMi = DistanceUtility.KILOMETRES_PER_MILE;
can prevent instantiation by declaring a private constructor
Preventing Instantiation
27
Version 2 (prevent instantiation)
28
public class DistanceUtility
{// attributes
public static final double KILOMETRES_PER_MILE = 0.621371192;
// constructors
// suppress default ctor for non-instantiation
private DistanceUtility()
{}
}
[notes 1.2.3]
Version 2.1 (even better)
29
public class DistanceUtility
{// attributes
public static final double KILOMETRES_PER_MILE = 0.621371192;
// constructors
// suppress default ctor for non-instantiation
private DistanceUtility()
{
throw new AssertionError();
}
}
[notes 1.2.3]
private
30
private attributes, constructors, and methods cannot be accessed by clients they are not part of the class API
private attributes, constructors, and methods are accessible only inside the scope of the class
a class with only private constructors indicates to clients that they cannot use new to create instances of the class
Puzzle 2
31
what does the following program print?
public class Puzzle02 { public static void main(String[] args) {
final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);}
}