Test 1 Flashcards
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 Distance Utility KILOMETRES_PER_MILE : double attribute type
Java Class
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 class
To decide what attributes and methods a class must provide, you need to understand the problem you are trying to solveThe attributes and methods you provide depends entirely on the requirements of the problem
Utility class
In Java, a utility class is a class having only static attributes and static methods Uses:Group related methods on primitive values or arrays java.lang.Mathor java.util.ArraysGroup static methods for objects that implement an interface java.util.Collections Group static methods on a finalclassMore on this when we talk about inheritance
utility class diagram
«_space;utility»_space;
DistanceUtility + KILOMETRES_PER_MILE : double + kilometresToMiles(double) : double + kilometresToMiles(double[]) : double[] + milesToKilometres(double) : double
—————————————————————————
Class name preceded by «_space;utility»_space;+ means public (– means private)Attributes: typeMethods:parameters and return type
general class structure
// any needed package statement // any needed import statements public class SomeName { // the attribute section // the constructor section // the method section }
DistanceUtility
public class DistanceUtility { // attributes public static final double KILOMETRES_PER_MILE = 1.609344;}
attribute
public static final double KILOMETRES_PER_MILE = 1.609344;
An attribute is a member that holds dataA constant attribute is usually declared by specifying1.modifiers 1.access modifier public
2.static modifier static
3.final modifier final 2.type double 3.nameKILOMETRES_PER_MILE4.value1.609344
Attribute names must be unique in a class The scope of an attribute is the entire class public attributes often called “fields” [API]
A public attribute
is visible to all clientspublic attributes break encapsulation A NothingToHide object has no control over the value of xClients can put a NothingToHideobject into an invalid state13 public class NothingToHide { public int x; // always positive } // client of NothingToHide NothingToHide h = new NothingToHide(); h.x = 100; h.x = -500; // x not positive
A public attribute makes a class brittle in the face of change
public class NothingToHide { private int x; // always positive } // existing client of NothingToHide NothingToHide h = new NothingToHide(); h.x = 100; // no longer compiles public attributes are hard to changeThey are part of the class APIChanging access or type will break existing client code
Avoid public attributes
in production code
Except when you want to expose constant value types
static attribute
An attribute that is staticis 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 Also commonly called class variable
a client should access
A client should 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
if no constructor specified
If you do not define any constructors, Java will generate a default no-argument constructor for you
preventing instatiation
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 DistanceUtilityobject double kmPerMi = DistanceUtility.KILOMETRES_PER_MILE; Can prevent instantiation by declaring a private constructor
private
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
final
An attribute (or variable) that is final can only be assigned to oncepublic static final attributes are typically assigned when they are declared public static final double KILOMETRES_PER_MILE = 1.609344;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 immutable types are constant final attributes of mutable types are not logically constant; their state can be changed
String is
immutable
It has no methods to change its contents
Avoid using mutable types
as public constants
A method
A method is a member that performs an actionA method has a signature (name + number and types of the parameters) kilometresToMiles(double)All method signatures in a class must be unique public static double kilometresToMiles(double km) A method returns a typed value or void double Use return to indicate the value to be returned public static double kilometresToMiles(double km) { double result = km / KILOMETRES_PER_MILE; return result; }
parameter
Sometimes called formal parametersFor a method, the parameter names must be uniqueThe scope of a parameter is the body of the method
method that is static
A method that is staticis a per-class member Client does not need an object to invoke the methodClient uses the class name to access the method double miles = DistanceUtility.kilometresToMiles(100.0);static methods are also called class methods A static method can only use static attributes of the class
invoke a method
A client invokes a method by passing arguments to the methodThe types of the arguments must be compatible with the types of parameters in the method signature The values of the arguments must satisfy the preconditions of the method contract double kilometres = 100.0; double miles = 0.0; miles = DistanceUtility.kilometresToMiles(kilometres);
arguments vs parameters
Arguments are passed in a method callParameters are accessed within the method int x = 8; int y = 10; int max = Foo.max(x, y); // x and y are arguments public static int max(int a, int b) // in class Foo { return a > b ? a: b; // a and b are parameters // where a=x and b=y }
What if a parameter and attribute share the same name?
What if a parameter and attribute share the same name?Parameter takes priority public class Foo{ static int count; // attribute… public static void increment(int count){ count = count + count; // changes parameter, not attributeFoo.count = Foo.count + count; // changes attribute// this.count if Foo were not a Utility class} }
pass by values with primitive types
An invoked method runs in its own area of
memory that contains storage for its
parameters
Each parameter is initialized with the value of
its corresponding argument
The method body runs and the return value is
computed
The return value is then copied back to the
caller
The argument kilometres and the parameter
km have the same value but they are distinct
variables
When DistanceUtility.kilometresToMiles()
changes the value of km the value of kilometres
does not change
Java uses pass-by-value
for primitive and reference types An argument of primitive type cannot be changed by a method (e.g., no swapping of ints) An argument of reference type can have its state changed by a method
overloading
Suppose we want to provide a method to convert
many values stored in an array from kilometres to
miles
We can provide another method called
kilometresToMiles() as long as the signature is different
Providing multiple methods with the same name
but different signatures is called method
overloading
The intent of overloading is to provide flexibility
in the types of arguments that a client can use
method overloading
Simple rule A class can define multiple methods with the same name as long as the signatures are unique
Overloading
Everything other than the signature is ignored
in determining a legal overload
Loosely speaking, the compiler will select the
method that most closely matches the number
and types of the arguments
“The rules that determine which overloading is
selected are extremely complex. They take up
thirty-three pages in the language specification [JLS,
15.12.1-3], and few programmers understand all of
their subtleties.”
interfaces as generics
When specifying parameters for a method, one can use interfaces instead of classes as long as the interface declares the required functionality ◦ This allows for passing of objects from any implementing class ◦ Can allow for a type of collection (e.g., a Map) instead of an implementation (e.g., a TreeMap) public static int freq(List list) instead of public static int freq(ArrayList list) If the parameterized type (e.g., the type of element in a collection) is not known (or does not matter), one can specify a generic type ◦ Typically written as “E”, “T”, “K”, or “V” ◦ Can also be used to describe the return type public static int freq(List list) ◦ Declares as the type in the generic method “freq” public static T getLargest(List list) ◦ declares “freq” as a generic method, and its return type is also an object of type T Sometimes, restrictions are required on the type (e.g., elements must be comparable) public static > boolean smaller(List list) ◦ T must implement Comparable directly public static > boolean smaller(List list) ◦ Allows T if it (or one of its superclasses) implements Comparable directly
what to do about invalid arguments
As the author of a class, you have control over
how your method is implemented
What you cannot control is the value of the
arguments that clients pass in
A well written method will
1. Specify any requirements the client must meet with
the arguments it supplies → preconditions
2. Validate the state of any arguments without
preconditions and deal gracefully with invalid
arguments → validation
Preconditions
If a method specifies a precondition on one of
its parameters, then it is the client’s
responsibility to make sure that the argument it
supplies satisfies the precondition
If a precondition is not satisfied then the method can
do anything (such as throw an exception, return an
incorrect value, behave unpredictably, …)
For our method possible preconditions are:
km must not be null
km.length > 0
Note that the second precondition is more restrictive than the first
validation
Alternatively, the class implementer can relax
preconditions on the arguments and validate
the arguments for correctness
The implementer assumes the responsibility
for dealing with invalid arguments
Must check, or validate, the arguments to confirm
that they are valid
Invalid arguments must be accommodated in a way
that allows the method to satisfy its postconditions
In our example, a possible return value for a
null array is a zero-length array
loop invariant
A Boolean expression that is true (i.e., holds) at the beginning of every iteration of the loop Does not necessarily appear in code Typically derived for testing purposes and to prove correctness int pow = 1; int i = 0; while (i < exponent) { pow = pow * base; i++; } return pow ; Invariants: ◦ i >= 0 ◦ i <= exponent ◦ pow == ba
Testing
Imperative to test utility (and all) classes for
correctness
Compare calculated output with expected
output
◦ Identical result test passed
◦ Different result test failed
Testing requires multiple test cases to ensure
correct operation under various condition
with various inputs
Example: Test kilometresToMiles method