Interfaces are the ninja warriors of the Java programming language. Like ninjas, interfaces are masters of disguise, hiding their implementation details and leaving only their methods exposed to the outside world. They’re also incredibly versatile, able to adapt to any situation and provide the tools necessary to get the job done. And just like ninjas, interfaces are often used to achieve multiple objectives at once, enabling polymorphism and decoupling code from implementation details.
In this post, we’ll explore the world of interfaces in Java. We’ll cover everything from the basics of interfaces, to the differences between abstract classes and interfaces, to the quirks and advanced features of functional interfaces and marker interfaces. So sharpen your swords, put on your ninja gear, and let’s dive into the world of Java interfaces!
Junior Level
(click to see the answer)
–> What is an interface?
An interface is a collection of abstract methods that defines a contract for how a class should behave.
–> How is an interface different from a class in Java?
An interface is different from a class in that it only defines method signatures and constants without providing any implementation code, but it can also contain default and private methods in Java 8 and later versions.
–> How do you declare an interface in Java?
To declare an interface in Java, use the interface keyword followed by the interface name and a set of method signatures and/or constants.
–> What is the purpose of an interface?
The purpose of an interface is to define a contract for classes to implement. By implementing an interface, a class agrees to provide an implementation for all the methods declared in the interface.
–> What is the difference between an interface and an abstract class?
An abstract class can contain instance variables, while an interface can only have constants. An abstract class can have a constructor although neither the abstract class, nor the interface can be instantiated. Also, Java allows only for a single inheritance when it comes to classes but you can implement as many interfaces as you want.
–> Can an interface have fields?
Yes, an interface can have constant fields, which are declared using the static final keywords. However, it’s worth mentioning that using interfaces solely to define constant fields is an anti-pattern (“Constant Interface” pattern) and should be avoided.
–> Can a class implement multiple interfaces?
Yes, a class can implement multiple interfaces in Java. This allows for greater flexibility in designing classes that can interact with different types of objects.
–> What happens if a class does not implement all the methods of an interface it is supposed to implement?
If a class does not implement all the methods of an interface, it must be declared abstract, and any concrete subclasses must provide implementations for the missing methods.
–> Can you instantiate an interface in Java?
No, you cannot instantiate an interface in Java. An interface only defines method signatures and constants but does not contain any implementation code.
–> Can you extend an interface in Java?
Yes, you can extend an interface in Java using the extends keyword. When one interface extends another, it inherits all the methods and constants from the parent interface.
Mid Level
(click to see the answer)
–> What is multiple inheritance, and why is it not supported in Java?
Multiple inheritance is the ability of a class to inherit from more than one superclass. It is not supported in Java because it can lead to problems such as the diamond problem, where multiple superclasses have a common superclass, resulting in ambiguity.
–> How does Java achieve multiple inheritance through interfaces?
Java achieves multiple inheritance through interfaces by allowing a class to implement multiple interfaces. Also, an interface can extend multiple other interfaces.
–> What is the difference between a default method and an abstract method in an interface?
A default method is a method in an interface that has an implementation. An abstract method is a method that is declared but has no implementation.
–> When and why were default methods in interfaces introduced in Java?
Default methods were introduced in Java 8. They allow for extending interfaces with new methods without breaking backwards compatibility. Also, they provide a default implementation for an interface method that is common across many implementing classes (reduce code duplication).
–> How do you override a default method in an interface?
To override a default method in an interface, you declare a method with the same name and signature in the implementing class and (#goodPractice) add an @Override annotation.
–> Can a static method be declared in an interface?
Yes, a static method can be declared in an interface. These methods can be called using the interface name, without the need for an instance of the implementing class.
–> Can an interface have a constructor?
No, an interface cannot have a constructor. Interfaces do not have instance variables, and therefore do not need constructors.
–> What is a functional interface in Java?
A functional interface in Java is an interface that has exactly one abstract method. Functional interfaces are often used to define lambda expressions or method references.
–> What is the use of the @FunctionalInterface annotation in Java?
The @FunctionalInterface annotation in Java is used to indicate that an interface is intended to be a functional interface. It helps to ensure that the interface only has one abstract method.
It is not required for an interface to be functional, but it serves as a documentation tool. Also, a compiler checks if a method annotated with @FunctionalInterface has only one new abstract methods.
–> Can a method in an interface throw an exception?
Yes, a method in an interface can throw an exception. The exceptions that a method in an interface can throw must be declared in the method signature.
–> What is the difference between a constant and a static final field in an interface?
The main difference between static final field (which has an implicit default access modifier) and a constant (which is public static final) is that a constant can only be called by the Interface while the static final can be called by the Interface and the Class that implements it.
Senior Level
(click to see the answer)
–> What is the role of the Object class in Java?
The Object class in Java is the root class of all classes in the Java class hierarchy. It provides several methods that are inherited by all classes, such as equals(), hashCode(), and toString().
The Object class defines the basic state and behaviour that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object’s class. (source: http://www.cis.upenn.edu)
–> How does the Object class relate to interfaces in Java?
Any methods defined in the Object class, such as the toString(), equals(), and hashCode(), are inherited by all interfaces. Interfaces are purely abstract contracts, but they still have methods from a concrete class such as Object.
It is because interfaces in Java are intended to describe behaviour, and many of the methods declared in the Object class are fundamental to the behaviour of all objects in Java. Having the methods from the Object class available in interfaces provides a level of convenience and consistency in Java programming.
–> Can an interface extend another interface?
Yes, an interface can extend another interface in Java using the extends keyword.
–> How do you declare a nested interface in Java? Why would you use them?
To declare a nested interface in Java, simply declare the interface within the curly braces of the enclosing class.
Nested interfaces can be a useful tool for organising and encapsulating related interfaces within a class or interface, and for ensuring type safety in your code.
–> What is the difference between a tagged interface and a normal interface?
A tagged interface (AKA marker interface) in Java is an interface that does not have any methods, but is used to “tag” classes with a certain property or behaviour. A normal interface in Java has one or more method declarations.
–> Can an interface be used as a parameter or return type of a method?
Yes, an interface can be used as a parameter or return type of a method in Java. Using an interface as a parameter or return type allows a method to accept or return any object that implements that interface, regardless of its specific implementation class. It’s an example of polymorphism.
–> How do you implement an interface in a class in Java?
To implement an interface in a class in Java, use the implements keyword followed by the name of the interface. The class must then provide implementations for all the methods declared in the interface or be abstract itself.
–> Can you make a non-static inner class implement an interface?
Yes, a non-static inner class can implement an interface in Java. This allows the inner class to provide a custom implementation for the methods declared in the interface.
–> What is the use of the @Override annotation when implementing an interface method?
The @Override annotation is used to indicate that a method in a class is intended to override a method declared in an interface. While it’s not required, it is considered a good practice because it allows the compiler to check if the method signature is correct.
–> Can you provide a default implementation for a method in a sub-interface that overrides a default method in a super-interface?
Yes, you can provide a default implementation for a method in a sub-interface that overrides a default method in a super-interface. However, the sub-interface method must use the default keyword to indicate that it is a default method.
Super Senior Level
(click to see the answer)
–> What is the diamond problem in multiple inheritance, and how does Java avoid it using interfaces?
The diamond problem is a problem that arises when a class inherits from two or more classes that have a common superclass. In Java, a class or an interface can implement (or extend when it’s an interface) two or more interfaces. If those interfaces have default methods with the same signature, the compiler will not know which implementation to choose.
It is then required for the class implementing/interface extending those interfaces to explicitly pick the implementation of the method or to override it altogether.
–> Can an interface have private methods in Java, and what is their use case?
Yes, an interface can have private methods in Java, since Java 9. These methods are used to provide common implementation code for default methods in the interface, without exposing the implementation to the implementing classes.
–> What is a mixin and how it’s achieved in Java?
In Java, a mixin is a class that provides a specific functionality to other classes without inheriting from them or being part of their inheritance hierarchy. Essentially, a mixin is a way to add functionality to an object without using inheritance. It’s achieved by implementing an interface that defines the behaviour of the mixin, and then using that interface to add the behaviour to an object.
–> How do you create a lambda expression from an interface in Java?
To create a lambda expression from an interface in Java, you simply write the parameter list, followed by the arrow ->, and then the method body. The interface must be a functional interface, with only one abstract method.
–> What is the use of the @Deprecated annotation in an interface in Java?
The @Deprecated annotation in an interface in Java is used to indicate that the interface or a particular method or field in the interface is no longer recommended for use and may be removed in future versions of the API.
–> Can an interface be generic in Java, and how do you declare it?
Yes, an interface can be generic in Java. To declare a generic interface, simply use angle brackets after the interface name to specify the type parameter.
–> What is the difference between an interface and a functional interface in Java?
An interface in Java can have any number of abstract methods, while a functional interface in Java has exactly one abstract method. Functional interfaces are often used with lambda expressions.
–> What is the use of the @Override annotation when implementing an interface method in Java?
The @Override annotation when implementing an interface method in Java is used to indicate that the method is intended to override a method declared in an interface. This helps to catch errors at compile-time if the method signature in the interface changes.
–> What is the difference between a sealed interface and a regular interface in Java 17?
A sealed interface in Java 17 is a type of interface that restricts which classes can implement it (with the keyword permits. This helps to enforce encapsulation and prevent unauthorized access to the interface.
–> How can you implement a strategy pattern using interfaces in Java?
To implement a strategy pattern using interfaces in Java, you define an interface for the strategy and then provide different implementations of the interface for different strategies. You can then pass different instances of the interface to the context object, which uses the appropriate strategy based on the situation.
–> Can you provide a default implementation for a method in an interface that is not a default method in Java 8?
No, you cannot provide a default implementation for a method in an interface that is not a default method in Java 8 or earlier versions. However, starting from Java 9, interfaces can have private methods, which can be used to provide common implementation code for default methods.
–> What is the purpose of the Comparable interface in Java?
The purpose of the Comparable interface in Java is to provide a way to order objects of a class. It defines the compareTo() method, which is used to compare two objects and return a negative, zero, or positive integer depending on their relative order.
–> What is the Cloneable interface in Java, and how is it used?
The Cloneable interface in Java is an empty interface that indicates that a class can be cloned using the clone() method. It is used to provide a way to create a copy of an object without invoking its constructor.
–> How do you implement an interface in an enum in Java?
To implement an interface in an enum in Java, simply add the implements clause followed by the interface name after the enum declaration. The enum must then provide implementations for all the methods declared in the interface.
–> What is the difference between a functional interface and a lambda expression in Java?
A functional interface in Java is an interface that has exactly one abstract method. A lambda expression in Java is a shorthand notation for creating an instance of a functional interface. Lambda expression are implementations of the functional interface’s abstract method.
–> What is the use of the @FunctionalInterface annotation in Java?
The @FunctionalInterface annotation in Java is used to indicate that an interface is intended to be a functional interface. It helps to ensure that the interface only has one abstract method, which is necessary for the interface to be used with lambda expressions.
–> Can an interface have a static initializer block in Java, and how does it work?
No, an interface cannot have a static initializer block in Java. The documentation states that interfaces can only have constant variables, which are implicitly static and final, and default methods starting from Java 8.
–> Can an interface have a non-static initializer block in Java, and how does it work?
No, an interface cannot have a non-static initializer block in Java. Interfaces do not have instance variables, and therefore do not need non-static initializer blocks.
–> How can you use interfaces to implement the Adapter pattern in Java?
To use interfaces to implement the Adapter pattern in Java, you define an interface that represents the required interface of the client code. You then create a class that adapts the interface of the adaptee object to the required interface using the adapter interface. The adapter class implements the adapter interface and delegates calls to the adaptee object.
About commonly used interfaces
(click to see the answer)
–> What is the purpose of the Collection interface in Java, and how does it relate to other interfaces such as List and Set?
The Collection interface in Java represents a group of objects, and it is the parent interface of List, Set, and other collection interfaces. It defines methods such as add(), remove(), and contains() that are common to all collection types.
–> How do you use the Iterator interface in Java to traverse elements in a collection?
To use the Iterator interface in Java to traverse elements in a collection, you first obtain an Iterator object from the collection using the iterator() method. You can then use methods such as hasNext() and next() to iterate over the elements in the collection.
–> What is the Comparable interface in Java, and how is it used to sort objects?
The Comparable interface in Java is used to define a natural ordering of objects. It defines the compareTo() method, which compares two objects and returns a negative, zero, or positive integer depending on their relative order. Objects that implement Comparable can be sorted using methods such as Collections.sort().
–> What is the purpose of the Cloneable interface in Java, and how can it be used to create clones of objects?
The Cloneable interface in Java is used to indicate that a class supports cloning. It is an empty interface, but its presence is checked using the clone() method. Objects that implement Cloneable can be cloned using the clone() method.
–> What is the Serializable interface in Java, and how is it used to make objects serializable for network transmission or persistent storage?
The Serializable interface in Java is used to indicate that a class can be serialized. It is an empty interface, but its presence is checked during serialization. Objects that implement Serializable can be serialized to a stream of bytes, which can be transmitted over a network or stored in a file for later use.
–> What is the Runnable interface in Java, and how is it used to create threads?
The Runnable interface in Java is used to define a task that can be run in a separate thread. It defines the run() method, which contains the code that will be executed in the new thread. To create a new thread, you can pass an instance of a class that implements Runnable to a Thread object and then call its start() method.
About Functional interfaces
(click to see the answer)
–> What is a functional interface in Java, and how is it different from a regular interface?
A functional interface in Java is an interface that has only one abstract method. It is used to define a single function or operation. A regular interface in Java can have any number of methods, including multiple abstract methods.
–> What is the purpose of the @FunctionalInterface annotation in Java, and when should you use it?
The @FunctionalInterface annotation in Java is used to indicate that an interface is intended to be a functional interface. It is not required, but it is recommended to use it to make the purpose of the interface clear to other developers.
–> What is the Predicate interface in Java, and how is it used to evaluate a boolean expression on an input?
The Predicate interface in Java is a functional interface that represents a boolean-valued function that takes one argument and returns a boolean. It is used to evaluate a boolean expression on an input.
–> What is the Function interface in Java, and how is it used to transform an input into an output?
The Function interface in Java is a functional interface that represents a function that takes one argument and returns a result. It is used to transform an input into an output.
–> What is the BiFunction interface in Java, and how is it used to transform two inputs into an output?
The BiFunction interface in Java is a functional interface that represents a function that takes two arguments and returns a result. It is used to transform two inputs into an output.
–> What is the Consumer interface in Java, and how is it used to perform an action on an input?
The Consumer interface in Java is a functional interface that represents a function that takes one argument and returns no result. It is used to perform an action on an input.
–> What is the Supplier interface in Java, and how is it used to supply an output?
The Supplier interface in Java is a functional interface that represents a function that takes no arguments and returns a result. It is used to supply an output.
–> How can you compose multiple functional interfaces together in Java to create more complex operations?
To compose multiple functional interfaces together in Java, you can use methods such as andThen() or compose() to combine the output of one functional interface with the input of another. This can be used to create more complex operations and pipelines of transformations.
About Marker interfaces
(click to see the answer)
–> What is a marker interface in Java, and how does it differ from a regular interface?
A marker interface in Java is an interface that has no methods. It is used to mark or tag a class or an object with some metadata or attribute. A regular interface, on the other hand, has one or more methods that must be implemented by the implementing class.
–> What is the purpose of a marker interface in Java?
The purpose of a marker interface in Java is to provide some metadata or attribute to a class or an object at runtime, which can be used for various purposes such as serialization, persistence, security, or reflection.
–> What are some examples of marker interfaces in Java, and how are they used?
Some examples of marker interfaces in Java are Serializable, Cloneable, RandomAccess, Remote, SingleThreadModel, Transient, and RemoteObject. They are used to mark or tag a class or an object with some metadata or attribute, which is used by the Java runtime or other frameworks for various purposes.
–> What is the Serializable interface in Java, and how is it used to make an object serializable for network transmission or persistent storage?
The Serializable interface in Java is a marker interface that indicates that a class can be serialized into a stream of bytes for network transmission or persistent storage. It is used to enable the Java runtime to serialize and deserialize objects of the class automatically.
–> What is the Cloneable interface in Java, and how is it used to create clones of objects?
The Cloneable interface in Java is a marker interface that indicates that a class can be cloned to create a new instance with the same state. It is used to enable the Java runtime to create a shallow copy of an object of the class using the clone() method.
–> What is the RandomAccess interface in Java, and how is it used to determine if a collection is random access or sequential access?
The RandomAccess interface in Java is a marker interface that indicates that a collection provides fast random access to its elements using the get() method. It is used to enable algorithms and optimizations that depend on random access to the collection.
–> What is the Remote interface in Java, and how is it used to define remote methods in a distributed computing environment?
The Remote interface in Java is a marker interface that indicates that a method can be invoked remotely in a distributed computing environment using Java RMI. It is used to enable the Java runtime to create proxies and stubs for the remote objects and to handle the network communication transparently.
–> What is the SingleThreadModel interface in Java, and how is it used to ensure thread safety in a Servlet environment?
The SingleThreadModel interface in Java is a marker interface that indicates that a Servlet can handle only one request at a time in a single thread. It is used to ensure thread safety in a Servlet environment by avoiding concurrent access to shared resources.
–> What is the Transient interface in Java, and how is it used to exclude fields from serialization?
The Transient interface in Java is a marker interface that indicates that a field should not be serialized into a stream of bytes for network transmission or persistent storage. It is used to exclude sensitive or irrelevant fields from serialization.
–> What is the RemoteObject interface in Java RMI, and how is it used to export remote objects?
The RemoteObject interface in Java RMI is a marker interface that indicates that a remote object can be exported to the RMI runtime for remote access. It is used to enable the Java runtime to create proxies and stubs for the remote objects and to handle the network communication transparently.
There you have it, guys. Once you know the answers to all the questions above, you’ll become a real Interfaces ninja. Remember, those questions do not by any means cover all there is to it when it comes to the topic of interfaces in Java. If any question seems unclear, don’t be afraid to dig deeper.
Soon, you’ should’ll have a solid understanding of the role interfaces play in Java and how to use them to write better code. So go forth and become a true ninja of Java interfaces!
