Interface in Java

⇒ Definition :-

Interface is similar to class. It also contains methods and fields but methods are by default abstract. Interface are the blueprint of class which specify that what a class must do but not explain how to do.Some of the important points about interface

  1. Interface is the blueprint of class.
  2. By default all the methods are ‘public’ and abstract in interface.
  3. By default compiler put public static final before fields.
  4. Interface keyword is used to declare interface.
  5. Interface provide total abstraction.
  6.  Any class which implements the interface must need to implement all the abstract methods declared interface.
  7. Implement keyword is used for the implementation of Interface.
  8. We can’t create the object of the interface same as the abstract class.
  9. Multiple Inheritance can be implemented by
  10. It can be used to achieve loose coupling.

Syntax for Interface

Interface interface_name

{

// declare constant fields

// declare methods that abstract

// by default

}

Program to demonstrate the working of interface

Interface I1

{

void show();

}

class Test implements I1

{

public void show()

{

System.out.println("interface function is implemented");

}

public static void main(String[] args)

{

Test t = new Test();

t.show();

}

}

Output:-

I1 is implemented

I2 is implemented 

Java Interfaces Interview Questions

In this article, we will cover some of the interview questions with their justification on the Java interface. These are most frequently asked interview question from OOPS concepts

Interfaces and OOP questions are very common in interviews. Make sure you get through some of the most important interview questions. This section covers the Java Abstract Class and Interface Interview Questions.

What is Interface in Java? OR Explain Interface in Java?

Till the Java 7 version,

  • An interface in Java is a pure abstract class which means all methods are abstract and variables are constants
  • By default, all methods inside an interface are public & abstract and variables are public, static & final
  • An interface is a means to achieve full abstraction in Java

Post-Java 8 release,

  • An interface can contain default and static methods, in addition to abstract methods
  • Though it looks too similar to abstract classes they are actually different in many ways
  • Read more about Java 8 default and static methods in Interface in detail
Can we instantiate an interface?
  • No, we cannot instantiate an interface
  • Since interface doesn’t have a constructor and contains only abstract methods and constants, therefore, we don’t need to instantiate
  • Instead implementing classes provide concrete implementation for these abstract methods and constants can be accessed using <interfaceName>.<variableName>

Post-Java 8 release,

  • In addition to abstract methods and constants, Java 8 introduced default and static methods
  • default methods can be accessed using implementing class’s reference object
  • static methods can be accessed using interface name i.e.; <interfaceName>.<staticMethodName>
  • Read more about Java 8 default and static methods in Interface in detail
Can we create an object for an interface?
  • No, we cannot create an object of an interface

Q) What happens if we define a concrete method inside Interface?

Till the Java 7 version,

  • A compilation error will be thrown stating below the reason
  • Compile-time error: Abstract methods do not specify a body
Interface Interview Questions & Answers Updated 1

Post-Java 8 release,

  • Concrete method (method with the body) are allowed with default or static keyword prefixed, as shown below
  • Otherwise, even in Java 8 compilation error will be thrown as seen below screen capture
Interface Interview Questions & Answers Updated 2

Can a method inside an interface be declared as final?

  • By default, methods declared inside an interface are public & abstract even if we don’t declare it explicitly compiler adds this modifier during compilation time
  • An interface allows only public & abstract modifiers in a method declaration
  • If final keyword added in method declaration then the compiler will throw an error as seen in the below screen capture
  • Compile-time error: Illegal modifier for the interface method display; only public & abstract are permitted
Interface Interview Questions & Answers Updated 3

Post-Java 8 release,

  • Still, the final modifier is not allowed in any of the methods in interface i.e.; abstract, default & static methods
  • Compile-time error: Illegal modifier for the interface method display; only public, abstract, default, static and strictfp are permitted
Interface Interview Questions & Answers Updated 4

What happens if we don’t initialize variables inside Interface?

  • Compiler throws an error stating final variable needs to be initialized
  • As variables defined inside an interface are by default public, static & final. So, the final variable always needs to be initialized where it is declared
  • Compile-time error: The blank final field <fieldname> may not have been initialized
Interface Interview Questions & Answers Updated 5
  • No change even post Java 8 release

Can we declare members as private or protected modifier inside Interface?

  • Variables (members) defined inside an interface are by default public, static & final
  • Therefore, no other access-modifier allowed except public
  • During the compilation process, compiler inserts/ add a public, static & final keyword for variables
  • These are interface variables and are accessed using the interface name
  • For example, <interfaceName>.<memberName> from any other class
  • No change even post Java 8 release too

How can we access variables defined inside Interface?

  • Members defined inside the interface can be accessed using interface name from any other class
  • For example, <interfaceName>.<memberName> from any other class
  • No change even post Java 8 release too

Can we modify variables defined inside Interface?

  • Since variables defined inside the interface are final therefore we cannot change the value of these variables anywhere (simple OOPS concept)
  • If we try to change the value, the compiler throws an error
  • Compile-time error: The final field <interfaceName>.<fieldName> cannot be assigned
  • No change even post Java 8 release too

Can we re-assign a value to a field of interface?

  • Re-assigning fields throw a compile-time error as these are final by default
  • Compile-time error: The final field <interfaceName>.<fieldName> cannot be assigned

What modifiers are allowed for methods in an interface?

  • Till the Java 7 version, only public & abstract are permitted
  • Post-Java 8 release, only public, abstract, default, static and strictfp are permitted

Is it ok to add an “abstract” keyword to interface definition?

  • Yes, we can actually add an abstract keyword to interface definition (somewhat similar to abstract classes)

Whether class compiles successfully if we don’t implement any of the abstract methods from Interface?

  • No, the compilation error will be thrown
  • If a class implements an interface then it must provide a definition or concrete implementation for every abstract method

Post-Java 8 release,

  • Still, implementing class must provide a definition or concrete implementation for every abstract method in an interface
  • Exceptional being default and static methods; it is okay if we don’t override the default method
  • Read more about Java 8 default and static methods in Interface in detail

What is the best possible solution if we don’t want to implement a few of the abstract methods from Interface?

  • The best solution is to declare the implementing class as abstract; compilation will succeed
  • But next inheriting class (i.e.; extending this class) must provide concrete method implementation or declare again as abstract.
Release Also: Abstraction in Java

basics of inheritance in java 2022

Java Interview Questions For Fresher

Can we reduce the visibility of the methods while implementing an interface?

  • By default abstract methods declared inside an interface are public
  • As per overriding rule, access visibility of the methods can be widened further
  • So, it is must declare overriding methods as public; as no other access visibility is wider than public
  • Read more about Java overriding rules here

Can we declare a constructor inside the interface?

  • A compilation error will be thrown stating “Interfaces cannot have constructors”
  • Compile-time error: Interfaces cannot have constructors

Can an interface be final?

  • No, an interface cannot be final and compilation error will be thrown
  • Compile-time error: Illegal modifier for the interface <interfaceName>; only public and abstract are permitted

Can interface extend any class?

  • No, an interface cannot extend any class
  • An interface can only extend one or more other interfaces

Can an interface implement any other interface?

  • No, an interface cannot implement another interface
  • An interface can only extend one or more other interfaces

Can an Interface extend another interface?

  • Yes, an interface can extend one or more interfaces

What is a marker interface or tagged Interface?

  • An interface with no fields or methods is known as a marker interface
  • A marker interface is used to indicate or provide essential information to JVM or compiler
  • Alternatively, it is referred to as a tagged interface
  • java.io.Serializable or java.lang.Cloneable is an example of a marker or tagged interface
  • Marker interface improves readability in comparison with any other alternatives

Can an interface contain another interface as a member?

  • Yes, an interface can contain another interface
  • This is referred to as Nested interface

What is Nested Interface in Java?

  • An interface declaration contained inside another class or interface is known as Nested interface
  • During compilation, compiler inserts/add the static keyword to the nested interface

DemoInterfaceA.java

  • public interface DemoInterfaceA {
  • String NAME = “Softwaretestingo.com”;
  • // Nested interface inside another interface
  • interface NextedItfExample {
  • }

In this article, we will cover some of the interview questions with their justification on Java 8 interface. These are most frequently asked interview question from OOPS concepts

Java 8 Interface Questions

What are the default methods in Java 8?

  • With the release Java 8, the new cool feature is added i.e.; if any new method needs to be added then provide the default implementation for this new method inside interface itself
  • This new method will be prefixed with “default” keyword and known as a default method
  • In Java 8, default methods are alternatively referred to as Virtual Extension methods or defender methods
  • Example of the default method

InterfaceInJava8.java

  • // only public &amp; abstract are permitted
  • public interface InterfaceInJava8
  • {
  • // old abstract method
  • void displayAbstractMethod(); // by default, this is public and abstract
  • // default method with concrete implementation from Java 8
  • default void displayDefaultMethod()
  • {
  • System.out.println(“InterfaceInJava8 : default method impl inside interface”);
  • }
  • }

Is it ok to define default methods in Java 8 without the “default” keyword inside the interface?

  • No, for defining the default method inside interface “default” keyword is must and it should prefix method declaration
  • Without prefixing default keyword results in a compilation error
  • Compile-time error: Abstract methods do not specify a body
  • Reason: without default keyword, compiler consider it as an abstract method and as said abstract methods don’t have a body

Whether multiple inheritances possible i.e.; implementing 2 or more interfaces?

  • Java allows multiple inheritances through interfaces i.e.; a class can implement 2 or more interfaces
  • Post-Java 8 release,
  • With the introduction of default methods, the ambiguity problem might arise when both interfaces have the same method with exactly the same signature

What happens in multiple inheritances from Java 8?

  • In Java 8, a class can implement 2 or more interfaces and this might arise ambiguity problem with the introduction default method inside interface
  • Ambiguity problem arises because; both interfaces can have the same method with exactly the same signature

What happens if a class implements 2 interfaces having exactly the same “default” method with the same signature?

  • Results in ambiguity problem with a compiler throwing error
  • There are 2 interfaces having the same default methods and a class implements both these interfaces and results in ambiguity problem

DemoInterfaceA.java

Interface Interview Questions & Answers Updated 9

DemoInterfaceB.java

Interface Interview Questions & Answers Updated 10

TestMultipleInheritance.java

Interface Interview Questions & Answers Updated 11
  • Compile-time error: Duplicate default methods named displayDefaultMethod with the parameters () and () are inherited from the types DemoInterfaceB and DemoInterfaceA

How can we resolve the ambiguity problem in Java 8 while implementing multiple Interfaces?

  • To resolve the ambiguity problem in Java 8, override the conflicting method
  • Now, if we want to invoke the default method from any of the interfaces then call using super keyword
  • For example, <interfaceName>.super.<defaultMethodName>

How to invoke one of the interface’s default methods while implementing two interfaces?

  • Using super keyword
  • Syntax: <interfaceName>.super.<defaultMethodName>

How to come overcome, multiple inheritance problems in Java 8?

  • Override the default method in the implementation class
  • Altogether provide new implementation or
  • Invoke either one of the default method using super keyword
  • For example, <interfaceName>.super.<defaultMethodName>

What happens if a class implements 2 interfaces having the exact same method with the same signature (consider one as default and another abstract)?

  • Compilation fails with an error saying the conflicting method
  • Compile-time error: The default method displayDefaultMethod() inherited from DemoInterfaceA conflicts with another method inherited from DemoInterfaceB
  • To overcome this error, override this conflicting method and provide new implementation or invoke default method’s implementation using super keywordInterface Interview Questions & Answers Updated 13

Can we declare the static method inside the interface?
Answer:
 Yes, we can declare starting from Java 8

Is it ok, to define a static method inside the interface?

Till the Java 7 version,

  • Defining any concrete method (method with the body) inside interface will throw compilation error, even if it’s a static method

Post-Java 8 release,

  • Static methods are allowed to define inside interface
  • This is a new feature added in Java 8 which will act as a helper method

How can we access static methods inside Interface?

  • Using interface name
  • Syntax: <interfaceName>.<variableName>

What is the interface in Java and what are its uses?
Ans: The interface in Java is similar to a class, which may contain a method’s signature only but not bodies and it is a formal set of methods and constant declarations that must be defined by the class that implements it. Interfaces are useful for:

  • Declaring methods that one or more classes are expected to implement.
  • Capturing similarities between unrelated classes without forcing a class relationship.
  • Determining an object’s programming interface without revealing the actual body of the class.

Class C implements Interface ‘I’ containing method m1 and m2 declarations. Class C has provided the

implementation for method m2. Can an object of Class C be created?
Ans: No. Class C should provide the implementation for all the methods in the interface ‘I’. Since Class C didn’t provide the implementation for the m1 method, it has to be declared as abstract. Abstract classes can’t be instantiated.

Can a method inside an interface be declared as final?
Ans: No. Doing so will result in compilation error. “public” and “abstract” are the only applicable modifiers for the method declaration in an interface.

Can an interface implement another interface?
Ans: Interfaces don’t provide implementation hence an interface cannot implement another interface.

Can an Interface extend another interface?
Ans: Yes. An Interface can inherit another Interface, for that matter, an Interface can extend more than one Interface.

Can a class extend more than one class?
Ans: No. A class can extend only one class but can implement any number of interfaces.

Can an interface be final?
Ans: No. Doing so will result in a compilation error.

Can a class be defined inside an interface?
Ans: Yes. It’s possible.

Can an interface be defined inside a class?
Ans: Yes. It’s possible.

What is a Marker Interface?
Ans: An interface which doesn’t have any declaration inside, but still enforces a mechanism is known as Marker Interface.

Can we define private and protected modifiers for variables in interfaces?
Ans: No. We cannot define private and protected modifiers for variables in interfaces

What is Externalizable?
Ans: Externalizable is an interface that extends Serializable Interface and sends data into Streams in compressed format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in).

What modifiers are allowed for methods in an interface?
Ans: Only “public” and “abstract” modifiers are allowed for the methods in the interfaces.

When can an object reference be cast to an interface reference?
Ans: When the object implements the referenced interface, an object reference is cast to an interface reference.

What is the difference between an Interface and an Abstract class?
Ans: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Can an anonymous class be declared as implementing an interface and extending a class?
Ans: An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

What is an abstract class?
Ans: An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

If you found any missed interview questions then you can inform us by a comment on the comment box.

Release Also: Abstraction in Java

basics of inheritance in java 2022

Java Interview Questions For Fresher

Leave a Comment