

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks. This article is contributed by Nitsdheerendra.

#Java interface code#

These are the two main reference types in Java.Īn interface can contain a subset of what a normal class can contain. Testinterface1 obj = new testinterface1() Īn interface is a reference type, just like a class is. You would inherit from these classes almost exactly the same way: public class InheritsFromInterface To illustrate that point, look at the following code. I mentioned earlier that interfaces are just a special form of an abstract class. Likewise, z is of type interfaceB and there is no interfaceMethodA() in interfaceB. The reason you can't do this is that y is of type interfaceA, and there is no interfaceMethodB() in interfaceA. However, you could never do the following: public void testInterfaces() prints "interfaceB, interfaceMethodB, implementation B"

prints "interfaceA, interfaceMethodA, implementation B" prints "interfaceB, interfaceMethodB, implementation A" prints "interfaceA, interfaceMethodA, implementation A" ImplementingClassB v = new ImplementingClassB() ImplementingClassA u = new ImplementingClassA() Now if you wanted you could write a method like this: public void testInterfaces() ("interfaceB, interfaceMethodB, implementation B") ("interfaceA, interfaceMethodA, implementation B") ("interfaceB, interfaceMethodB, implementation A") ("interfaceA, interfaceMethodA, implementation A") Many classes can implement an interface, and a class can implement many interfaces: interface InterfaceA To use this interface, you simply need to implement the interface. So the interface above is identical to the interface below: public interface Interface Since the interface can't implement any methods, it's implied that the entire thing, including all the methods, are both public and abstract (abstract in Java terms means "not implemented by this class"). However, it can be achieved with interfaces, because the class can implement multiple interfaces. 2) Java does not support 'multiple inheritance' (a class can only inherit from one superclass). In Java, you create an interface like this: interface Interface 1) To achieve security - hide certain details and only show the important details of an object (interface). An interface is a special form of an abstract class which does not implement any methods.
