Java OCA OCP Practice Question 2384

Question

Given

interface Printable {}
class Shape implements Printable {}
class Box implements Printable {}
class Factory {/*from  w  ww .ja  v a  2 s .  co  m*/
    static Printable getInstance(String type) {
        if (type.equals("Box"))
            return new Box();
        else if (type.equals("Shape"))
            return new Shape();
        else
            return getPrintable();
    }
    private static Printable getPrintable() {
        return new Shape();
    }
}

Select code that initializes an Printable reference using a Factory:.

a  Printable animal = Factory.getInstance();
b  Printable animal = Factory.getPrintable();
c  Printable animal = Factory.getInstance("Printable");
d  Printable animal = Factory.getPrintable("Box");
e  Printable animal = new Factory().getInstance("Shape");


c, e

Note

Class Factory doesn't expose the object creation logic of Printable objects and uses the Factory pattern to create and return its instances.

Option (a) won't compile.

Though you might dismiss it as a trivial or tricky option, note that it's easy to find similar options on the exam.

Options (b) and (d) won't compile because getPrintable() is a private method and it doesn't define the method parameters.

Option (e) is correct.

A static method can be accessed using both the class name and an instance.




PreviousNext

Related