Explore key concepts behind interfaces in Java, including their purpose, declaration, and what they can contain. This quiz covers fundamental interview topics about interfaces with practical examples for beginners.
What best describes an interface in Java?
Explanation: An interface is described as a set of rules a class must follow, enabling shared behaviors. Variables, keywords, and data storage are not the main concepts of interfaces, making those options incorrect.
Why are interfaces used in Java?
Explanation: Interfaces enable different classes to share the same behaviors, as shown in the example with devices like TV and sound systems. The other options are unrelated to the main purpose of interfaces.
How do you declare a simple interface named 'RemoteControl' in Java?
Explanation: The correct way to declare an interface uses the 'interface' keyword. 'class' and 'object' are for classes or objects, not interfaces, and 'RemoteControl interface' is incorrect syntax.
In the remote control example, what does the interface provide to devices like TVs?
Explanation: The interface provides actions (methods) such as power on or off for devices to implement. It does not specify how actions are performed or provide variables or constructors.
What must a class do when it implements a Java interface?
Explanation: Classes must provide bodies (implementations) for all interface methods. The other options are incorrect because interface methods are not ignored, and interface variables are not private or data members.
By default, what is true about methods defined inside a Java interface before Java 8?
Explanation: Before Java 8, interface methods are abstract and do not have method bodies. They are not private, do not initialize variables, and do not require a body.
Which access modifier applies to interface methods by default?
Explanation: Interface methods are public by default to ensure they can be implemented by any class. 'Protected', 'Private', and 'Final' are not the default for interface methods.
What new types of methods were allowed in Java interfaces starting with Java 8?
Explanation: From Java 8, interfaces can have default and static methods. Instance variables, constructors, and synchronized blocks are still not permitted as part of an interface's method set.
What type of variables can you define inside a Java interface?
Explanation: Interfaces can have public static final variables (constants). They cannot contain instance variables, protected variables, or dynamic local variables.
What benefit do interfaces give classes regarding shared behaviors?
Explanation: Interfaces help classes share behaviors through the same method signatures. They do not force identical implementations, enable constructor inheritance, or prevent using abstract classes.