Test 1 Flashcards

1
Q

Design a class to convert between kilometres and miles

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Java Class

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Designing class

A

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 depends entirely on the requirements of the problem

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Utility class

A

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.ArraysGroup static methods for objects that implement an interface java.util.Collections Group static methods on a finalclassMore on this when we talk about inheritance

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

utility class diagram

A

&laquo_space;utility&raquo_space;
DistanceUtility + KILOMETRES_PER_MILE : double + kilometresToMiles(double) : double + kilometresToMiles(double[]) : double[] + milesToKilometres(double) : double
—————————————————————————
Class name preceded by &laquo_space;utility&raquo_space;+ means public (– means private)Attributes: typeMethods:parameters and return type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

general class structure

A
// any needed package statement
// any needed import statements
public class SomeName { 
// the attribute section
// the constructor section 
// the method section }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

DistanceUtility

A
public class DistanceUtility {     // attributes    public static final double 
KILOMETRES_PER_MILE = 1.609344;}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

attribute

A

public static final double KILOMETRES_PER_MILE = 1.609344;
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.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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

A public attribute

A

is visible to all clientspublic attributes break encapsulation A NothingToHide object has no control over the value of xClients 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

A public attribute makes a class brittle in the face of change

A
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 changeThey are part of the class APIChanging access or type will break existing client code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Avoid public attributes

A

in production code

Except when you want to expose constant value types

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

static attribute

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

a client should access

A
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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

if no constructor specified

A

If you do not define any constructors, Java will generate a default no-argument constructor for you

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

preventing instatiation

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

private

A

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

17
Q

final

A
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 = 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
18
Q

String is

A

immutable

It has no methods to change its contents

19
Q

Avoid using mutable types

A

as public constants

20
Q

A method

A
A method is a member that performs an actionA 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;   }
21
Q

parameter

A

Sometimes called formal parametersFor a method, the parameter names must be uniqueThe scope of a parameter is the body of the method

22
Q

method that is static

A

A method that is staticis a per-class member Client does not need an object to invoke the methodClient 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

23
Q

invoke a method

A

A client invokes a method by passing arguments to the methodThe 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);

24
Q

arguments vs parameters

A

Arguments are passed in a method callParameters 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 }

25
Q

What if a parameter and attribute share the same name?

A

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} }

26
Q

pass by values with primitive types

A

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

27
Q

Java uses pass-by-value

A
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
28
Q

overloading

A

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

29
Q

method overloading

A
 Simple rule
 A class can define multiple methods with the same 
name as long as the signatures are unique
30
Q

Overloading

A

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.”

31
Q

interfaces as generics

A
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
32
Q

what to do about invalid arguments

A

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

33
Q

Preconditions

A

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

34
Q

validation

A

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

35
Q

loop invariant

A
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
36
Q

Testing

A

 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