Prev Next

Java / Interface

1. Can a class be defined inside an Interface? 2. Advantages of Inner Interface. 3. What are the access modifiers applicable for the nested interface declared inside a class? 4. Can an interface inherit/extend multiple interface? 5. Example of a nested interface from Java API. 6. Inner Interface in Java. 7. Can an Interface implement another interface? 8. Are interfaces also inherited from Object class? 9. What is a Marker(Tag) Interface? 10. Are Nested interfaces declared static? 11. can we have non-static inner interface? 12. Syntax for inner interface. 13. Should the nested interface must be public? 14. Can we define a class inside an interface? 15. Advantage of having a class inside an interface. 16. What is the difference between an Abstract class and Interface? 17. Can a method inside a Interface be declared as final or static in Java? 18. Can an Interface extend another Interface? 19. Why interface is allowed to extend multiple interface whereas class can inherit only one class? 20. Can an Interface be final? 21. Give few examples of a marker interface? 22. Can I define private and protected variables in an interface? 23. What is Externalizable? 24. Difference between Serializable and Externalizable. 25. Does Externalizable extends Serializable interface? 26. Can you specify the accessibility modifier for methods inside an interface? 27. What is abstract Interfaces in Java? 28. Can a interface define static initializer in Java ? 29. What is functional interface in Java 8. 30. Why do we implement interfaces in Java? 31. What are the rules for writing lambda expressions in Java 8? 32. What is SAM interface in Java 8? 33. How will you call a default method of an interface in a class? 34. Explain type inference in Java 8. 35. Explain the difference between lambda expression and anonymous class in terms of “this” reference. 36. What is Optional in Java8? 37. Can we initialize Optional value as null in Java8? 38. Difference between Optional flatMap() and map() in Java8. 39. Does interface uses all Object class methods? 40. Can interface have instance fields? 41. Can interface have instance method? 42. How JVM invoke special behavior in case of marker interface? 43. How to write your own marker interface? 44. Can we have private interface method? 45. Can an interface have main method? 46. Can you modify the value of an interface field? 47. Can we have private method/static method in Interface ?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

Can a class be defined inside an Interface?

Yes.

package com.javatutorials.accessModifer.protectedPackage;

public interface MyMainInterface {

	public class MyClass {
		public static void method() {
			System.out.println("Class method inside an interface.");
		}

		void nonStaticmethod() {
			System.out.println("Instance method inside an interface.");
		}
	}

}

class Mainclass {
	public static void main(String[] args) {
		MyMainInterface.MyClass.method();

		MyMainInterface.MyClass myClass = new MyMainInterface.MyClass();
		myClass.nonStaticmethod();
	}
}

Advantages of Inner Interface.

  •      promotes Encapsulation.
  •      Organise interfaces and facilitate logical grouping of related interfaces.
  •      improves readability

What are the access modifiers applicable for the nested interface declared inside a class?

Inner interface (aka) nested interface can have any access modifier when declared inside a class.

Can an interface inherit/extend multiple interface?

Yes.

package com.tutorials.interfaceExample;
public interface MyInterface extends ParentInterface1, ParentInterface2 {
               void method();
}
class ImplementingClass implements MyInterface {
               @Override
               public void method() {
                              System.out.println("HI");
               }
}
interface ParentInterface1 {
               void method();
}
interface ParentInterface2 {
               void method();
}

Example of a nested interface from Java API.

java.util.Map has inner interface Entry.

public static interface Map.Entry<K,V>

Inner Interface in Java.

Inner interface also known as nested interface, refer to the interfaces that are declared inside an another interface or class.

Can an Interface implement another interface?

No. Interface doesn't provide implementation hence it is not possible.

However an Interface can extend (inherit) another interface, also multiple interface

public interface MyMainInterface extends ParentA, ParentB {

}

interface ParentA{
	
}
interface ParentB{
	
}

Are interfaces also inherited from Object class?

No, only classes in java are inherited from Object class. Interfaces in java are not inherited from Object class. But, classes which implement interfaces are inherited from Object class.

An interface implicitly declares one method for each public method in Object. This way the equals and Object class method is implicitly declared as a member in an interface.

What is a Marker(Tag) Interface?

An Interface which doesn't have any declaration inside (no methods) but still enforces a mechanism.

Marker interfaces are also referred as Null interfaces.

Are Nested interfaces declared static?

Yes. Implicitly it is static.

can we have non-static inner interface?

No.

Syntax for inner interface.

An interface inside a interface.

interface outer_interface_name{
 interface inner_interface_name{  //static and public implicitly
 }
}

An interface inside a class.

class outer_class_name{ 
 
               interface nested_interface_name{  //implicitly static
 
  }
} 

Should the nested interface must be public?

Yes, when the nested interface is declared inside another interface.
Because, there is no other way to use the nested interface, other than the external module.

Can we define a class inside an interface?

Yes, you can create both a nested class or an inner class inside a Java interface.

interface InterfaceName {
	class ClassName {
	}
}

Advantage of having a class inside an interface.

It limits the scope of the class to where it belongs. Class inside an interface is tightly coupled with the interface.

What is the difference between an Abstract class and Interface?
  • Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
  • An class can implement any number of interfaces, but subclass at most one abstract class.
  • An abstract class can have non abstract methods. All methods of an interface are abstract.
  • An abstract class can have instance variables. An interface cannot.
  • An abstract class can define constructor. An interface cannot.
  • An abstract class can have any visibility: public, protected, private or none (package). An interface’s visibility must be public or none (package).
  • An abstract class inherits from Object and includes methods such as clone() and equals().
Can a method inside a Interface be declared as final or static in Java?

No. An interface method can have only public, abstract, and static (from Java8) modifiers. final keyword is not allowed since it prevents overriding.

Prior to Java8, static methods in the interface was not allowed. With Java 8, interfaces can have static methods as well as instance methods. So static modifier can be used since Java8.

Can an Interface extend another Interface?

Yes.

Why interface is allowed to extend multiple interface whereas class can inherit only one class?

Java doesn't allow multiple inheritance, so a class can extend only one Class. But an interface is a pure abstraction model and doesn't have inheritance hierarchy like classes.

Can an Interface be final?

No.

Give few examples of a marker interface?

Some of the marker interfaces are Serializable, Remote, Cloneable.

Can I define private and protected variables in an interface?

No.

What is Externalizable?

Externalizable is an Interface that extends Serializable Interface. It sends data into Streams in Compressed Format.

It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Difference between Serializable and Externalizable.

Serializable is a marker interface as it has defined no members while Externalizable is not as it has two methods.

Does Externalizable extends Serializable interface?

Yes.

Can you specify the accessibility modifier for methods inside an interface?

All the methods inside an interface are always implicitly public and abstract. public and abstract can be mentioned explicitly whereas other access modifier are not allowed.

What is abstract Interfaces in Java?

Interfaces marked with abstract modifiers are abstract interfaces.

Every interface is implicitly abstract. This modifier is obsolete and should not be used in new programs.

Can a interface define static initializer in Java ?

No. interfaces cannot have initializers.

What is functional interface in Java 8.

An interface with only one abstract method is known as functional interface. For example, Runnable and Callable interface are functional interface as it has only one method.

A functional interface can have default and static methods while it has only one abstract method.

Why do we implement interfaces in Java?

Using interfaces keeps the use of chunks of functionality consistent. So when another class wants to use your class, it can act on it as a cloneable, disposable object without worrying about your implementation details.

What are the rules for writing lambda expressions in Java 8?
  • A lambda expression can have 0, 1 or more parameters.
  • The parameter's type can be explicitly declared or it can be inferred from the context implicitly.
  • Multiple parameters are enclosed in parentheses and delimited by commas. Empty parentheses represents an empty set of parameters.
  • With single parameter, if its type is inferred, it is not required to use parentheses.
  • The lambda expression body can contain 0, 1 or more statements.
  • If the body of lambda expression has single statement, curly parenthesis is optional and the return type of the anonymous function is the same as that of the body expression. When there is more than one statement in body than these must be enclosed in curly brackets.
What is SAM interface in Java 8?

Functional Interface is also known as SAM Interface, it contains only one abstract method. SAM Interface stands for Single Abstract Method Interface.

How will you call a default method of an interface in a class?

Using super keyword along with interface name.

interface A {
    default void foo() {
        System.out.println("A.foo");
    }
}
public class B implements A {
    @Override
    public void foo() {
        System.out.println("B.foo");
    }

    void aFoo() {
        A.super.foo();
    }

    public static void main(String[] args) {
        B b = new B();
        b.foo();
        b.aFoo();
    }
}

Explain type inference in Java 8.

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument that makes the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.

Explain the difference between lambda expression and anonymous class in terms of “this” reference.

With an inner class, it creates a new scope. You can overwrite local variables from the enclosing scope by instantiating new local variables with the same names. You can also use the keyword “this” inside your inner class as a reference to its instance.

However, lambda expressions work with enclosing scope. You can’t overwrite variables from the enclosing scope inside the lambda’s body. In this case, the keyword “this” is a reference to an enclosing instance.

What is Optional in Java8?

Java 8 introducd Optional in java.util package that represents if a value is present or absent. The main advantage is No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications.

Can we initialize Optional value as null in Java8?

Yes, but it’s a bad practice. The main intention of Optional is to eliminate null referencing.

Difference between Optional flatMap() and map() in Java8.

Use map if the function returns the object you need or flatMap if the function returns an Optional.

Does interface uses all Object class methods?

Yes. Although interfaces does not inherit from Object class, an interface implicitly declares a public abstract member method corresponding to each public instance method declared in the Object class. These abstract members may be overridden by "interface implementing class" or its parent Object class.

Hope this answer helps.Thanks for reaching out to Javapedia.net. if you still need some additional information, let us know.

Can interface have instance fields?

No. All the fields are implicitly public, static and final.

Can interface have instance method?

Yes, interface can have default methods from Java8 onwards.

How JVM invoke special behavior in case of marker interface?

Let consider Serializable interface as an example. Serialization is handled by the ObjectInputStream and ObjectOutputStream classes. These classes will check your class whether or not it implementes Serializable, Externalizable. If yes it will continue or else will thrown NonSerializableException.

How to write your own marker interface?

We can create our own marker interface by creating an interface with no method. This marker interface has nothing to do with JVM, we add the special logic in market interface handler class by using instanceOf check.

interface IMarker{    }

class MarkerImpl implements IMarker{
      //do some task
}

class Main{
         public static void main(String[] args){
            MarkerImpl ob = new MarkerImpl();
             if (ob instanceOf IMarker){
                // do some task
           }
       }
}
Can we have private interface method?

Yes, private static interface methods are supported from Java 9 onwards. The default and the abstract methods cannot be private.

Can an interface have main method?

Yes, from Java8, interface allows static method. So we can write main method and execute it.

Can you modify the value of an interface field?

No. The interface fields are final and static implicitly.

Can we have private method/static method in Interface ?

Yes, from Java 9 onwards we can have private methods in interface.

«
»
Abstract Class

Comments & Discussions