OCP Flashcards – 2. Advanced Java Class Design

OCP Exam Objective 2 ‚Äď Advanced Class Design

Flashcard OCP.2.Advanced.Java.Class.Design.001

What does the enum keyword stand for?

Click here to view answer
The enum keyword is short for enumerated values or a list of values.

 

Flashcard OCP.2.Advanced.Java.Class.Design.002

Is it possible to use enums in switch statements?

Click here to view answer
Yes, it is. Note, however, that case clauses accept only enum values that are not qualified any further with the enum‘s name, so the case Season.WINTER below does not compile.

Also observe that if a list of values is all that is in the enum, the semicolon after the values is optional.

Illustration:

enum Season{
    WINTER, SPRING, SUMMER, FALL,
}
class Test{
    public static void main(String[] args) {
        Season ssn = Season.SPRING;
        switch(ssn){
           case Season.WINTER: System.out.println("Ski time!");     // INVALID: enum's name not allowed here
           case SUMMER: System.out.println("Let's go swimming!");
        }
    }
}

 

Flashcard OCP.2.Advanced.Java.Class.Design.003

Is it possible to compare enumerated values directly to ints?

Click here to view answer
No, it is not because enums are objects.

 

Flashcard OCP.2.Advanced.Java.Class.Design.004

What can enums declare?

Click here to view answer
Enums are allowed to have instance variables, constructors, and methods.

 

Flashcard OCP.2.Advanced.Java.Class.Design.005

What is the restriction imposed on enum‘s constructor(s)?

Click here to view answer
The constructors are required to be private (or – ostensibly! – package private because in the absence of the private access modifier the compiler will automatically mark the ctor as private during compilation.)

 

Flashcard OCP.2.Advanced.Java.Class.Design.005

Are value-specific methods allowed for enums?

Click here to view answer
Yes, enums can also have value-specific methods, which implies that the enum itself should declare that method. It can be:

  • abstract, meaning that all enum values¬†will have to¬†provide an implementation,
  • concrete, in which case enum values can choose whether they want to override the default implementation.
enum Season{
    WINTER,
    SPRING,
    SUMMER { public void say(){ System.out.println("Pool time!"); }},
    FALL;
    void say(){ System.out.println("Zzz..."); }
}
class Test{
    public static void main(String[] args) {
        Season season = Season.SUMMER;
        switch(season){
            default: Season.WINTER.say();
            case SUMMER: season.say();
        }
    }
}

 

Flashcard OCP.2.Advanced.Java.Class.Design.006

How many nested class types are in Java?

Click here to view answer
There are four types of nested classes:

  • static nested classes (for brevity in explanations, Igor sometimes calls them “stincas”)
  • member inner classes (“incas”)
  • local inner classes (“locas”)
  • anonymous classes (“anoncas”)

 

Flashcard OCP.2.Advanced.Java.Class.Design.007

What are main characteristics of static nested classes?

Click here to view answer
  • static nested classes can exist without an instance of the outer class.
  • They cannot access the enclosing class instance variables.
  • HINT: it really helps to think of them as regular top-level classes that are placed¬†inside another¬†top-level class for packaging convenience.

 

Flashcard OCP.2.Advanced.Java.Class.Design.008

What are main characteristics of member inner classes?

Click here to view answer
  • They cannot exist without an instance of the outer class;
  • Are instantiated with code such as

outerObject.new Inner();

  • Can access private members of the outer class;
  • May access static members but only if those members are compile-time constants;
  • Cannot define any static members because the inner class itself is associated with an instance.

 

Flashcard OCP.2.Advanced.Java.Class.Design.009

What are main characteristics of local inner classes?

Click here to view answer
  • Local inner classes are classes defined within a method;
  • Just like member inner classes, they can also access private members of the outer class;
  • Are allowed to access final or effectively final local variables.

 

Flashcard OCP.2.Advanced.Java.Class.Design.010

What are main characteristics of anonymous inner classes?

Click here to view answer
  • Anonymous inner classes are a special type of a local inner class that does not have a name;
  • They may either extend exactly one class or implement exactly one interface;
  • Local inner classes are scoped to the end of the current block of code;
  • Like member inner classes, they are not allowed to have static members except for compile-time constants;
  • REMINDER: an anonymous inner class declaration must end with a semicolon.

 

Flashcard OCP.2.Advanced.Java.Class.Design.011

What is a functional interface?

Click here to view answer
A functional interface is one that has exactly one abstract method (EXTRA: which hasn’t its namesake in Object).

 

Flashcard OCP.2.Advanced.Java.Class.Design.012

What is a design principle?

Click here to view answer
It is an established idea or best practice that facilitates the software design process, such as:

  • DRY (“Don’t Repeat Yourself”)
  • YAGNI (“You Aint’ Gonna Need It”)
  • SOLID:
    • Single Responsibility Principle: must be only one reason to change;
    • Open/Closed Principle: open for extension but closed for modification;
    • Liskov Substitution Principle: subtypes must be substitutable for their base types;
    • Interface Segregation Principle: clients should not be forced to depend on methods that they do not use;
    • Dependency Inversion Principle: high level modules should not depend on low level modules, but both should depend on abstractions.

 

Flashcard OCP.2.Advanced.Java.Class.Design.013

What is a design pattern?

Click here to view answer
A design pattern is an established general solution to a commonly occurring software development problem. Examples:

  • Singleton Pattern
  • Immutable Object Pattern

 

Flashcard OCP.2.Advanced.Java.Class.Design.014

What is a Singleton?

Click here to view answer
Singleton is a creational design pattern that “…ensures that only one instance of a class is created, and provides a global point of access to it” (as per Design Patterns: Elements of Reusable Object-Oriented Software by GoF).

 

Flashcard OCP.2.Advanced.Java.Class.Design.015

When the Sigleton Pattern is used?

Click here to view answer
It is used in scenarios when you might need only one object of a class.

 

Flashcard OCP.2.Advanced.Java.Class.Design.016

How many classes are involved in the implementation of the Singleton Pattern?

Click here to view answer
Implementation of the Singleton Pattern involves a single class.

 

Flashcard OCP.2.Advanced.Java.Class.Design.017

What is the restriction that applies to the Singleton’s constructor?

Click here to view answer
A class that implements the Singleton Pattern must define its constructor as private.

 

Flashcard OCP.2.Advanced.Java.Class.Design.018

How would you declare a Singleton object?

Click here to view answer
A Singleton class uses a static private reference variable to refer to its sole instance.

 

Flashcard OCP.2.Advanced.Java.Class.Design.019

How would you access the Singleton object?

Click here to view answer
Through a static method that is defined in the Singleton class to access its sole instance.

 

Flashcard OCP.2.Advanced.Java.Class.Design.020

Offer real-world examples where the Singleton Pattern is implemented and/or used.

Click here to view answer
First off, single-value enums are perfect Singletons (and therefore can be used to implement your own Singletons). As for the Java core libraries, the Singletons are:

  • java.lang.Runtime#getRuntime() – Returns the runtime object associated with the current Java application.
  • java.lang.System#getSecurityManager() – Returns the system security interface.
  • java.awt.Desktop#getDesktop() – Returns the Desktop instance of the current browser context

Other typical examples can include a browser cache, a thread pool, a single instance of Device Manager to manage all the devices on your system, a single instance of a print spooler to manage all the printing jobs, etc.

 

Flashcard OCP.2.Advanced.Java.Class.Design.021

Which keyword is used to inherit members between interfaces?

Click here to view answer
extends

 

Flashcard OCP.2.Advanced.Java.Class.Design.022

How to override a final class’s methods?

Click here to view answer
Basically speaking, it cannot be done.

 

Flashcard OCP.2.Advanced.Java.Class.Design.023

Does the following lambda expression lack anything?

(ScubaDiver sd) -> return sd.isCertified();

Click here to view answer
The lambda expression misses the curly braces; it should be

(ScubaDiver sd) -> { return sd.isCertified(); }

 

Flashcard OCP.2.Advanced.Java.Class.Design.024

Consider the following definition:

abstract class Plant{}

Is it possible to instantiate this class?

Click here to view answer
No, but we could instantiate, for example, an anonymous class that extends the abstract Plant:

new Plant() { };

 

Flashcard OCP.2.Advanced.Java.Class.Design.025

What restricts implementation when using a final class?

Click here to view answer
A final class cannot be extended.

 

Flashcard OCP.2.Advanced.Java.Class.Design.026

How can a local class inside a static method access non-static members of its outer class?

Click here to view answer
It cannot.

 

Flashcard OCP.2.Advanced.Java.Class.Design.027

For what puirpose the @Override annotation is used?

Click here to view answer
To document that the current method is intended to override an existing method in the superclass.

 

Flashcard OCP.2.Advanced.Java.Class.Design.028

How would you create static members inside an inner class?

Click here to view answer
That’s impossible. An inner class cannot have any static declarations.

 

Flashcard OCP.2.Advanced.Java.Class.Design.029

How is an enum constructor invoked?

Click here to view answer
An enum constructor is invoked automatically when an enum value is first used.

 

Flashcard OCP.2.Advanced.Java.Class.Design.030

Which keyword is used to specify that a class cannot be extended, a field contains a constant value, or a method cannot be overridden?

Click here to view answer
final

 

Flashcard OCP.2.Advanced.Java.Class.Design.031

Which keyword must be used in a class declaration if any of its methods are marked as abstract?

Click here to view answer
abstract

 

Flashcard OCP.2.Advanced.Java.Class.Design.032

What modifiers can be applied to local variables?

Click here to view answer
Only final.

 

Flashcard OCP.2.Advanced.Java.Class.Design.033

Which method in the Enum class allows to retrieve an enumeration constant’s ordinal value?

Click here to view answer
ordinal()

 

Flashcard OCP.2.Advanced.Java.Class.Design.034

What operator separates parameters from the lambda expression’s body?

Click here to view answer
The arrow token, ->

 

Flashcard OCP.2.Advanced.Java.Class.Design.035

How to declare an enum inside a method?

Click here to view answer
It cannot be done because nested enum types are implicitly static.

 

Flashcard OCP.2.Advanced.Java.Class.Design.036

Which keyword must be used to allow implementation of abstract members of an abstract class?

Click here to view answer
extends

 

Flashcard OCP.2.Advanced.Java.Class.Design.037

In which way the contents of an abstract class differ from a concrete class?

Click here to view answer
An abstract class can contain abstract members, while a concrete class cannot.

 

Flashcard OCP.2.Advanced.Java.Class.Design.038

Is the following LOC valid?

enum Seasons { SPRING, SUMMER, FALL, WINTER }

Click here to view answer
Yes, because no semicolon is required as long as the enum contains only values; note that just like in case of arrays, we can have a trailing comma after the last value – but this is not on the exam…

 

Flashcard OCP.2.Advanced.Java.Class.Design.039

What keywords are used to implement interface methods?

Click here to view answer
implements and extends:

interface One{
    void run();
}

interface Two extends One{
    @Override
    default void run(){}
}

 

Flashcard OCP.2.Advanced.Java.Class.Design.040

How do the contents of an abstract class differ from those of an interface?

Click here to view answer
Usual answer in pre-1.8: an abstract class can contain implementation, while an interface cannot.

Since 1.8: an abstract class can contain fields

 

Flashcard OCP.2.Advanced.Java.Class.Design.041

Which method in the Enum class provides a way to iterate over enumeration constants?

Click here to view answer
The values() method (which is an implicitly declared method synthesized by the compiler).

 

Flashcard OCP.2.Advanced.Java.Class.Design.042

Which generic interface provides a single boolean-returning method to be used in lambda expressions?

Click here to view answer
Predicate

 

Flashcard OCP.2.Advanced.Java.Class.Design.043

What is missing from the following lambda expression?

x -> x.getValue();

Click here to view answer
Actually, nothing:

class Test{
    String greeting = "Hello!";
    Predicate<String> pred = x  -> x.isEmpty()          ;   // semicolon ain't part of LE
    Consumer<String>  cons = x  -> System.out.println(x); 
    Supplier<String>  supp = () -> "Hi there!"          ;
    
    boolean check(String str, Predicate<String> pred){
        return pred.test(str);
    }
    
    void consume(String str, Consumer<String> cons){
        cons.accept(str);
    }
    
    String supply(Supplier<String> supp){
        return supp.get();
    }
            
    void run(){
        check  (greeting, x  -> x.isEmpty()            );    // no semicolon after SINGLE statement allowed
        consume(greeting, x  -> System.out.println(x)  );
        supply (          () -> "Salut!"               );
    }

    public static void main(String[] args) {
        new Test().run();                                    // Hello!
    }
}

REMINDER: When dealing with a Predicate, follow the Semirebra Rule (ref.to Nailing 1Z0-808, page 392)

 

Flashcard OCP.2.Advanced.Java.Class.Design.044

Which restriction concerns objects when using an abstract class?

Click here to view answer
An abstract class cannot be instantiated.

 

Flashcard OCP.2.Advanced.Java.Class.Design.045

Are private members of an outer class available to an inner class?

Click here to view answer
Yes, they are.

 

Flashcard OCP.2.Advanced.Java.Class.Design.046

How would you instantiate a member inner class?

Click here to view answer
Outer.Inner inner = new Outer().new Inner();

 

Flashcard OCP.2.Advanced.Java.Class.Design.047

In what ways lambda expressions differ from regular methods?

Click here to view answer
Lambdas are anonymous functions and, as such, do not have names, but they do have a body and also can specify parameters.

 

Flashcard OCP.2.Advanced.Java.Class.Design.048

How would you interpret the following LOC?

Outer.Sinner sinner = new Outer.Sinner();

Click here to view answer
It’s an instantiation of a¬†static nested class named Sinner that is defined in the Outer class.

 

Flashcard OCP.2.Advanced.Java.Class.Design.049

How would you interpret the following LOC?

System.out.println(“OCP”);

Click here to view answer
Apparently, the System class is public and has a public static field named out (whose type right now¬†may be¬†a mystery but actually it’s PrintStream), and the println(String str) method is available to this out object. The LOC in question invokes the abovementioned method¬†while passing to it a String object “OCP”.

How do we know that out is public and static ? Because we access it through the class name.

 

Flashcard OCP.2.Advanced.Java.Class.Design.050

In what cases interfaces should be used instead of abstract classes?

Click here to view answer
It should be done when

  • we expect that the interface will be implemented by many unrelated classes (examples:¬†Comparable, Iterable,¬†Cloneable…);
  • it is desirable to¬†specify the behavior of a particular data type without concerning ourselves with¬†who is going to implement its behavior;
  • we may want to take advantage of multiple inheritance mechanism.

Leave Comment

Your email address will not be published.