- All variables of an interface are
public static final
by default, so you can directly use them You can implement an interface by means of anonymous class (without using
implements
keyword)public static void main(String[] args) throws Exception{ System.out.println(I.s); // accessing Interface I's variable I i = new I() { @Override public int getS() { return 10; } }; System.out.println(i.getS()); // accessing I's method } interface I { String s = "test"; int getS(); }
Without Implement Keyword, Can we use interface?
-
03-06-2022 - |
Pregunta
Can We Use Variable and methods of Interface without using Keyword 'Implements'.
Note:Interface and Classes are in same Package.
Thanks in Advance..!!!
Solución
Otros consejos
An interface is a contract for a class to fulfil. If no class implements it then you're probably misusing the interface.
As pointed out you have access to static member variables, but I'd still question the need for such a design!
You can use the public static final
variables of the interface as constant definitions in your class without implementing the interface.
Using methods , would be useless without implementing those methods in the subclass , as interface only declares public
methods which are implicitly abstract. What will you do with just the method definition without any implementation ?
Interface are actually contract definitions, any class implementing the interface abides by the contract.
You can implement interface without the key word implements
by creating anonymous class. But again are implementing the interface through that class.
P.S: Please try this to assure yourself that interface can declare methods with abstract keyword , though its redundant.
interface A {
public abstract void method();
}