About Question enthuware.ocajp.i.v7.2.893 :
Posted: Tue Jul 02, 2013 4:09 pm
4. Given:
interface Worker {
void performWork();
}
class FastWorker implements Worker {
public void performWork(){ }
}
You are creating a class that follows "program to an interface" principle.
Which of the following line of code will you most likely be using?
Select 1 option:
a. public FastWorker getWorker(){
return new Worker();
}
b. public FastWorker getWorker(){
return new FastWorker();
}
c. public Worker getWorker(){
return new FastWorker();
}
d. public Worker getWorker(){
return new Worker();
}
Answer: c
Explanation:
a. This will not compile because Worker is an interface and so it cannot be instantiated.
Further, a Worker is not FastWorker. A FastWorker is a Worker.
c. This is correct because the caller of this method will not know about the actual class of the object that is returned by this method.
It is only aware of the Worker interface. Hence, if you change the implementation of this method to return a different type of Worker,
say SuperFastWorker, other classes do not have to change their code.
d. This will not compile because Worker is an interface and so it cannot be instantiated
---------
I selected option B.
The following code that compiles.
interface Worker {
void performWork();
}
class FastWorker {
public static void main(String[] args) {
FastWorker fw = new FastWorker();
fw.getWorker();
}
public FastWorker getWorker(){
return new FastWorker();
}
}
-----
Why is option B. incorrect?
interface Worker {
void performWork();
}
class FastWorker implements Worker {
public void performWork(){ }
}
You are creating a class that follows "program to an interface" principle.
Which of the following line of code will you most likely be using?
Select 1 option:
a. public FastWorker getWorker(){
return new Worker();
}
b. public FastWorker getWorker(){
return new FastWorker();
}
c. public Worker getWorker(){
return new FastWorker();
}
d. public Worker getWorker(){
return new Worker();
}
Answer: c
Explanation:
a. This will not compile because Worker is an interface and so it cannot be instantiated.
Further, a Worker is not FastWorker. A FastWorker is a Worker.
c. This is correct because the caller of this method will not know about the actual class of the object that is returned by this method.
It is only aware of the Worker interface. Hence, if you change the implementation of this method to return a different type of Worker,
say SuperFastWorker, other classes do not have to change their code.
d. This will not compile because Worker is an interface and so it cannot be instantiated
---------
I selected option B.
The following code that compiles.
interface Worker {
void performWork();
}
class FastWorker {
public static void main(String[] args) {
FastWorker fw = new FastWorker();
fw.getWorker();
}
public FastWorker getWorker(){
return new FastWorker();
}
}
-----
Why is option B. incorrect?