Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of creating a class inside interface and interface inside class

Tags:

I want to know what is the need of placing a class inside interface and an interface inside class?

class A {    interface B {} }  interface D {    class E {} }  
like image 763
Bhadri Avatar asked May 09 '11 04:05

Bhadri


People also ask

Can we create class inside a interface?

Yes, if we define a class inside the interface, the Java compiler creates a static nested class.

How do you create an interface inside a class?

Yes, you can define an interface inside a class and it is known as a nested interface. You can't access a nested interface directly; you need to access (implement) the nested interface using the inner class or by using the name of the class holding this nested interface.

Why do we create interface class?

Why do we use an Interface? It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. It is also used to achieve loose coupling.

What is the use of interface class?

In Java, an interface specifies the behavior of a class by providing an abstract type. As one of Java's core concepts, abstraction, polymorphism, and multiple inheritance are supported through this technology. Interfaces are used in Java to achieve abstraction.


1 Answers

This i am copying and pasting from some link (i earlier did and sharing with you) May be that can help you a bit.

1)

interface employee{ class Role{       public String rolename;       public int roleId;  } Role getRole(); // other methods  } 

In the above interface you are binding the Role type strongly to the employee interface(employee.Role). 2) With a static class inside an interface you have the possibility to shorten a common programming fragment: Checking if an object is an instance of an interface, and if so calling a method of this interface. Look at this example:

  public interface Printable {     void print();      public static class Caller {         public static void print(Object mightBePrintable) {                 if (mightBePrintable instanceof Printable) {                         ((Printable) mightBePrintable).print();                 }         }     } } 

Now instead of doing this:

  void genericPrintMethod(Object obj) {     if (obj instanceof Printable) {         ((Printable) obj).print();     } } 

You can write:

   void genericPrintMethod(Object obj) {          Printable.Caller.print(obj);     } 
like image 126
punamchand Avatar answered Oct 09 '22 19:10

punamchand