i learning java programming , beginner. learning interfaces now. came across below 2 simple examples , have doubt in those
program1
public interface callback { void callback(int param); } class client implements callback { // implement callback's interface public void callback(int p) { system.out.println("callback called " + p); } void nonifacemeth() { system.out.println("classes implement interfaces " + "may define other members, too."); } } class testiface { public static void main(string args[]) { callback c = new client(); c.callback(42); // c.nonifacemeth(); } }
program 2
class client implements callback { // implement callback's interface public void callback(int p) { system.out.println("callback called " + p); } void nonifacemeth() { system.out.println("classes implement interfaces " + "may define other members, too."); } } class testiface { public static void main(string args[]) { client c = new client(); c.callback(42); } }
both program1 , program2 give same output.
in program1, variable c declared of interface type , in program2, variable c declared of class type.
my doubt difference between these 2 programs , advantages of creating interface type variable ?
kindly me t understand concept. tia
i try keep short web full explainaions on interfaces.
interface contract. many classes can implement interface. using interface 1 way loosly couple code components.
in program1, variable c declared of interface type
this means implementation of interface can taken create concrete object , code should not break.
and in program2, variable c declared of class type.
this means have change code use right class every time need use different implementation. code cohesive.
it make more sense when start studing things dependency injection or factory pattern etc. helpful in unit testing.
update
based on comment
i want difference between these 2 statements "callback c = new client();" , "client c = new client();"
it conceptual @ moment callback c = new client()
allows change type of varible c
at time. lets there other implementation importantclient
in code interface used declare variable can @ time change c = new importantclient()
. can not if using client c = new client();
Comments
Post a Comment