I am going to implement an interface but I don't want to override all of its methods, what should I do to not having some methods without body in my code?
Printable View
I am going to implement an interface but I don't want to override all of its methods, what should I do to not having some methods without body in my code?
You just have to have an empty code body in your class.
The hwol idea of an interface is to force you to implement the methods.
Chris
The interfaces could be used for the inheritance between unrelated classes that are not part of the same hierarchy or anywhere in the hierarchy. Using the interface you can specify what to do a class but not how. A class can implement multiple interfaces. An interface can extend one or more interfaces using the keyword extends. All data members are public interface, static and final by default. An interface method can have only public, default modifiers.
You really need to override its methods... if dont want to have any code in its body, then just leave it blank.
I've been doing some reading on GUI's recently, and they involve interfaces when implementing the listener and the source of the Event. How is this relevant to your original question I hear you ask :p well in the afforementioned case you can bypass writing all the methods of the interface in your listener class if you use an 'adapter'. This is itself a class that houses all the methods of the relevant interface with blank bodies, you then have your listener extend said adapter - and over-ride the methods of the interface you do want to actually use.
The same process can be used in more general terms:
Code Java:public interface MyInterface { void method1(); void method2(); void method3(); }
Code Java:public class MyInterfaceAdapter implements MyInterface { MyInterfaceAdapter() { } void method1() {} void method2() {} void method3() {} }
Code Java:public class AnyRandomClass extends MyInterfaceAdapter { public AnyRandomClass() {} void method1 () { System.out.println("inside method1") } // only uses one of the methods, and thus only defines one of the methods. }
And presto, we have a class (AnyRandomClass) that implements an interface by means of inheritance. There fore allowing it to take advantage of polymorphism and what not. From this point on, you can keep on creating classes that extend the this adapter and again not have to implement all the methods of the interface that you don't need.