Below are important Question & Answers taken from the Q&A discussions in this section.
Q1. In the following code, both P & P1 define same method test, but with different return types. It gives a compilation error in class C. Is there a way out?
public interface P{
void test();
}
public interface P1{
int test();
}
public class C implements P, P1 {
void test() {
System.out.println("test");
}
}Answer: No, it cannot be resolved. test() in class C is not overriding P1.test(). Similarly, if you add a test() in class C with return type as int, then it would still not work as the new method will be considered as a duplicate of the other test() method, i.e., the method signatures are same and they differ only in return type. Realistically, I don't think we will ever encounter such a situation where two methods with same signatures, but different return types are inherited.
Q2. Since you can have a variable in an interface which is implicitly public, static and final, then I guess it is logically correct to have a static initializer block inside an interface, which gives me a compiler error. I know there are many alternate solutions for this but I need a logically correct answer. Can you help me with this?
Answer: I would strongly assume that it would be because interfaces are seen as pure contracts. Had they allowed static initializer blocks, then one would assume that those blocks would also run (i.e., interface is initialized) as soon as interface is loaded (happens when interface is accessed for the first time). In such scenarios, those static blocks might run some complicated code and that is not something that is expected of an interface by default as we expect interface to behave as a contract. But, interfaces variables can be initialized via a method call or can have static methods, which also run some code. However, in such cases, the client code is intentionally accessing those variables or static methods and is not constraining itself to use the interface as just a pure contract.
Q3. When do we use abstraction and encapsulation?
Encapsulation is simply bundling of data & methods into a single unit. This is done via a class in Java. So, it is used all the time in Java.
Abstraction is about specifying a contract, i.e., what methods can be invoked without getting into any implementation details of the methods. Interfaces & abstract classes help achieve abstraction. Although the term abstraction is not used in the course, the previous section and especially this one is all about abstraction. When you are creating a library for others to use, then most likely you will use abstraction as you would mostly define few interfaces. So, that's an example. In general, whenever you are defining some specification (service) for others (whether your own project or for public in general) to use, then abstraction would generally be there.