• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/67

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

67 Cards in this Set

  • Front
  • Back
What are the advantages of using a static factory method over a public constructor?
- static factory methods can have descriptive names that related the context of the item being returned (makes readability and maintenance better)

- Not required to create a new class on each innovcation (caching and singleton patterns)

- They can return a subtype of the declared return type (Factory pattern / implementation hiding / programming to interfacts)
What are the disadvantages of using a static factory method?
- Classes without public or protected constructors cannot be subclassed (limits inheritance)

- Can be difficult to distinguish from other static methods. Harder to use that constructors.
How does the static factory facilitate service provider frameworks such as JCE?
- The subtype returned by a static factory does not have to exist at compile time
- concrete class is registered in a properties file
- The static factory is passed a key which it uses to look up the class name
- Reflection is used to instantiate the concrete class
What is a singleton?
A class that can only be instantiated once
What is the advantage of using a static factory method over a public static member?
static factory allows you to change what is returned without changing the API. Encapsulating the member.
How to you enforce non-instantiability of a class (3) ?
definte a private constructor and ensure it is not called in the object. This can be used for class designed not to be instantiated, such as a collection of static methods (java.lang.Math).

Marking a class abstract does not ensure this as it could be extended and implemented.
Why is it beneficial to avoid creating duplicate objects (4) ?
Performance can often be increased by reusing immutable objects.
Why is it important to avoid finalizers (6) ?
- There is no guarantee that a finalizer will be executed propmptly. It is up to the garbage collector algorithm. Therefore, nothing time critical should be specified in a finalizer. This leads to portability issues also

- the JLS also provides no guarantee that the finalizer will run at all. you should not depend on a finalizer to maintain critical persistent state.

- if an uncaught exception is thrown during finalization; the exception is ignored and the finalizer is abruptly terminated
What can you use instead of a finalizer for clean up of resources and state?
Provide an explicit termination method. (e.g. close method on an OutputStream)

Note: one should use a private variable to track whether the object has been invalidated. Methods should check this flag and throw an InvalidStateException if improperly executing a method

Note: clients should typically include termination methods in a try...finally block when using such an object
What are valid uses of a finalizer() method?
- As a safety net to explicit termination methods if they are not called by the client

- To clean up native peers
Is "finalizer chaining" performed automatically when a subclass is finalized?
No - finalizer chaining must be performed manually. It is best to call a superclass finalizer method in a finally statement after performing subclass finalization
What is the Object method equals() used for?
For testing for "logical quality"

The equals method provides "deep comparison" by checking if two objects are logically equal as opposed to the "shallow comparison" provided by the equality operator ==.
what is the default implementation of equals() in the Object class?
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
When is it valid NOT to override the default equals() method?
- Each instance of a class is inherently unique. This is true for classes that represents active entites rather than "value" objects. i.e. Thread

- There is no need for a "logical" equality test. Makes no sense i.e. java.util.Random

- A superclass has already overridden the method and the behaviourly is still satisfactory

- The class is private or package-private and you are sure that equals will never be called (assumption!)
When is it appropriate to override equals()?
When a class as the notion of a logical equality and a superclass has not already implemented one.

This is typically true for value classes.

It also enables such a class to serve as a map keys and set elements with predictable behaviour
When you override the equals method, you must abide by the "general contract". What is the general contract?
* It is reflexive: for any non-null reference value x, x.equals(x) should return true.
* It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
* It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
* It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
* For any non-null reference value x, x.equals(null) should return false.
Define equality reflexivity. What is an example issue if reflexivity is not ensured?
Reflexivity simply states that an object must be equal to itself.

Adding an object to a collection and then doing a contains test. If no reflexivity then the collection would report that the object does not exist in the collection
Define equality symmetry?
Two objects must agree that they are equal
Define equality transitivity
If one object is equal to a second, and a second is equal to a third. Then the first object must be equal to the third
How should you handle transitivity and symmetry in a class hierarchy?
There is no way to extend an INSTANTIABLE class and add an aspect while preserving the equals contract.

Two approaches:
- Favour composition over inheritance
- extend from an abstract class
Define equality consistency
It states that two objects remain equal until such time as one or both are modified
What is the non-nullity equality test?
This states that an object must be unequal to null
What is the recipe for a good equals method
1. Use the == operator to check if the argument is a reference to the same object. If so, return true. This is a performance optimization

2. Use the instanaceof operator to check if the argument is of the correct type. If not, return false. instanceof will return false if null is passed

3. Cast the argument to the correct type

4. For each significant field in the class, check to see if the fields matchin the correspnding object. If so, return true. Otherwise false.

5. When you have finshed. Ask yourself whether the equals is symmetric, transitive and consistent
When must you override the hashCode method?
Any class that overrides equals() must override hashCode()
What is the hashCode() contract?
* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
* If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
* It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
What is the issue with returning a constant integer for a hashCode()?
Performance impacts - it would mean the any use of a hashed collection would result in every object being put into the same bucket. Effectively, turning the hash table into a linked list
What is a good recipe for a hashCode()?
1. Store a constant value

2. For each field, f, considered in the equals() method
a) Compute an int hash code
i) if boolean f ? 0 : 1
ii) if byte, char, short, int (int) f
iii) if long, compute (f ^ (f >>> 32))
iv) if float, f = Float.floatToIntBits(f)
v) if double, f = Double.doubleToLongBits(f) then hash as 2.a.iii
vi) if field is an object reference, recurse the hashCode field
vii) if array, treat each element as a seperate field

b. combine 37* result and add constant
Have can hashCode performance be improved for immutable objects?
Given they don't change, the hashCode can be pre-calculated and cached

private volatile int hashCode = 0;

public int hashCode() {
if (hashCode == 0) {
<calculate>
}
return hashCode;
}
What is the purpose of the cloneable interface?
The interface has no methods and marks the object as being cloneable. The Object.clone method checks for the presence of this interface and will throw a CloneNotSupportedException if not present
What is the purpose of the Comparable interface?
Comparable requires the implementation of the compareTo method which permits order comparisons. A class implementing this implies that is has the concept of natural ordering
What type of classes benefit greatly from implementing the Comparable interface?
Value classes with a natural sense of ordering
What are the provisions of the Comparable interface?
1.
a) If the first is greater than the second, then the second must be less than the first
b) if the first is less than the second, then the second must be greater than the first
c) if the first is equal to the second, then the second must be equal to the first.

2. if the first is greater than the second and the second is greater than the third, then the first must be great than the third (transitivity)

3. any objects compared as equal, must yield the same result when compared to another object
What is a characteristic of a well designed Module?
How well implementation and details are hidden. Clean separation between the API and the implementation
What are some benefits are encapsulation or information hidding at the module level?
- Speed up system developement as modules can be developed in parallel

- ease of maintenance as loosely coupled to other system modules

- better performance tuning opportunities

- increases software reuse

- decreases risk when building a large application
What mechanism is available in Java to assist with access control?
Access Modifiers
What rule of thumb should you use when assigned access to class and members?
Keep as inacessibile as possible. Use the lowest possible access
What are the two access levels for top level classes and interfaces?
Public and package-private
What are the four access modifiers for members?
private
default (package private)
protected
public
Which is preferrable and why. Public fields or getters-setters?
getter-setters as you can hide any implementation details and change implementation if necessary
Public static final fields are typically used for storing constants. What should be referenced by these fields?
either primitive values or immutable objects.
what is wrong with this constant declaration?

public static final Type[] VALUES = { }
a nonzero length array is mutable (contents can be changed). This is a potential security hole.

Make the field private and use the Collections.unmodifiableList(Arrays.asList(VALUE)) approach
What is an immutable class?
A class whose instances cannot be modified. All information is provided when it is created and is fixed for the lifetime of the object
What are the benefits of using an immutable class?
- easier to design. Immutable objects have exactly one state (the creation state)

- easier to implement

- less prone to error. Immutable objects are thread safe; they require no synchronisation

- more secure

- promotes reuse. Because an immutable object cannot be changed, it can be reused. this is facilitate by providing public static final contstants for frequent values. Additionally, static factories can be used to cache objects to avoid creation
What are the rules for making a class immutable?
1. Don't provide any methods that modify the object (mutators)

2. Ensure that no methods may be overridden. This prevents malicious subclasses

3. Make all fields final. This can be relax to mean all "externally visible" fields. It is possible to have internal private fields for computation purposes that may be mutable.

4. Make all fields private

5. Ensure exclusive access to any mutable components. If you class has any fields that refer to mutable objects, ensure that clients of the class cannot obtain references to these objects. Never initialise such a field to a client-provided object reference nor return the object reference from an accessor. Make defensive copies in constructors, accessors and readObject methods.
What is the functional approach and how does it relate to immutable classes?
The functional approach is one in which a method on an object returns a results of an operation with an operand without modifying the state of the object.

For example,

public Complex add(Complex c) {
return new Complex(re + c.re, im + c.im);
}

A new object is return rather than the modification of the existing object
What is a disadvantage of immutable classes?
A separate object instance is required for each distinct value. This can be costly in the object is large (i.e. a million bit BigInteger).

Small value classes should always be immutable. Large classes should also be immutable with the option of providing a public companion class if performance issues are being realised.
Give an example of when immutability is impractical?
Process classes such as Threads or TimerTask. However, the class should be as immutable as possible. reducing the state space reduces the likelihood of errors.
How does inheritance break encapsulation?
A subclass depends on the superclass implementation. If the superclass implementation changes, this could break the subclass.

Examples of superclass change include: introducing new methods, overriding methods

A superclass can be specifically designed to be extended.
What is an alternative to class inheritance?
Composition

The existing class becomes an private field on the new class
What is forwarding? What is a forwarding method?
Forwarding is the process by which a composing class forwards innvocations to the composed class

Forward Methods are in the new class that actually forward the innoivations to the underlying composed class
Composition and forwarding is also known as what?
Wrapping
What are the disadvantages of using a wrapper class?
- They are not suited for use in callback frameworks. Because the wrapped object does not know about its wrapper, it passes a reference to itself and bypasses the wrapper

- Tedium in writing forwarding methods
What does it mean for a class to be designed and documented for inheritance?
- The class must document precisely the effects of overriding any method. The class must document its self-use of overridable methods. This is usually represented in the doc commecing with the phrase "This implementation"

- a class may have to provide hooks into its internal workings in the form of judiciously chosen protected methods

- constructors must not invoke overridable methods

- Neither clone nor readOject may invoke an overridable method, directly or indirectly
What is the best way to handle concrete classes that are not designed and documented to be safely subclassed?
Prohibit subclassing

- declare the class as final

- make all constructors private or package-private and a public static factories
What two mechanisms are provided for defining a type that permits multiple implementations?
Inheritance and abstract classes
What are the differences between interfaces and abstract classes?
- An abstract class contains implementation, while an interface does not

- An abstract class requires subclassing, while a class can implement multiple interfaces
Describe how you would retrofit a class to implement a new interface?
You would use the implements keyword and then implement the desired methods.
Describe how you would retrofit a class to extend an new abstract class?
You would have to place the abstract class high up in the type hierarchy where it subclasses an ancestor of both classes
What is a mixin?
A mixin is a type that a class can implement in addition to is primary type that provides some optional behaviour. An example is comparable
How would you create a skeletal implementation of a interface?
Use an interface and abstract class in tandem. The abstract class would provide a skeleton implentation of the interface.

You could then either extend the abstract class or "wrap" a subclass
What is the constant interface pattern and why is it inappropriate?
A constant interface exposes no methods, rather a series of static final fields.

It is exposing implementation detail for consuming classes and can be difficult to get rid of once implemented in a class hierarchy (backwards compatability)
What are the best approaches for exposing constants?
- If they are tightly related to a class or interface, then add them there

- If they represent enums, then prefer an enum approach

- Move to a utility class
What is a nested class?
A class defined within another class
What are the four kinds of nested classes?
- static member class

- nonstatic member class

- anonymous class

- local class
What is a static member class?
It is a class declared inside another class and has access to all of the enclosing class' members, even those declared private. A static member class is a static member of its enclosing class and obeys the same accessibility rules as other static members. If it is declared private, it is accessible only within the enclosing class
What is a nonstatic member class?
Each instance of a nonstatic member class is implicitly associated with the enclosing instance.

Can invoke methods on the enclosing class

Cannot exist in isolation of the enclosing class

Typically created in the constructor of the enclosing class
What is a common use of a nonstatic member class?
To define an adapter that allows an instance of the outer class to be viewed as an instance of some unrelated class.

I.e. Map interface has nonstatic members to implement their collection views.