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 {} }
Yes, if we define a class inside the interface, the Java compiler creates a static nested 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 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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With