java - How would I overload method in an interface? -
if have interface
public interface someinterface { // method 1 public string getvalue(string arg1); // method 2 public string getvalue(string arg1, string arg2); } i want able pass in 1 or 2 string getvalue method without having override both in each implementing class.
public class someclass1 impelments someinterface { @override public string getvalue(string arg1); } public class someclass2 implements someinterface { @override public string getvalue(string arg1, string arg2); } this won't work because someclass1 needs implement method 2 , someclass2 needs implement method 1.
am stuck doing this?
public interface someinterface2 { public string getvalue(string... args); } public class someclass3 implements someinterface2 { @override public string getvalue(string... args) { if (args.length != 1) { throw illegalargumentexception(); } // code } } public class someclass4 implements someinterface2 { @override public string getvalue(string... args) { if (args.length != 2) { throw illegalargumentexception(); } // code } } someinterface2 someclass3 = new someclass3(); someinterface2 someclass4 = new someclass4(); string test1 = someclass3.getvalue("string 1"); string test2 = someclass4.getvalue("string 1, "string 2"); is there better way of doing this?
an interface serves contract users of interface: specify methods available (in all implementations) , how called. if 2 implementations of interface need different method, method should not part of interface:
public interface lookup { } public class maplookup implements lookup { public string getvalue(string key) { //... } } public class guavalookup implements lookup { public string getvalue(string row, string column) { // ... } } in program, know implementation use, can call right function:
public class program { private lookup lookup = new maplookup(); public void printlookup(string key) { // hardcoded lookup of type maplookup, can cast: system.out.println(((maplookup)lookup).getvalue(key)); } } alternative approach
if class program more generic , uses dependency injections, may not know implementation have. then, make new interface key, can either type of key:
public interface lookup { // ... public string getvalue(key key); } public interface key { } public mapkey implements key { private string key; // ... } public guavakey implements key { private string row, column; // ... } the dependency injection in program might come factory implementation. since cannot know type of lookup use, need single contract getvalue.
public interface factory { public lookup getlookup(); public key getkey(); } public class program { private lookup lookup; public program(factory factory) { lookup = factory.getlookup(); } public void printlookup(factory factory) { system.out.println((lookup.getvalue(factory.getkey())); } }
Comments
Post a Comment