java - accessing the unique methods of classes that implement an interface -
i have class called militaryreport implements reportable interface:
public class militaryreporter implements reportable { public string reportable_type(){ return "militaryreport"; } public string reportable_db_name() { return "military_reports"; } public void setuniqueattribute(int attr) { this.uniqueattribute = attr; } public int uniqueattribute(){ return some_unique_attribute_to_military; } }
i have class called oilreport implements reportable interface:
public class oilreport implements reportable { public string reportable_type(){ return "oilreport"; } public string reportable_db_name() { return "oil_reports"; } public int anotheruniqueattribute(){ return some_unique_attribute_to_oil; } }
this reportable interface:
public interface reportable { public string reportable_type(); public string reportable_db_name(); }
here's problem. reportable strategy belongs instance of report. report can have type of reportable e.g. military, oil, driver, etc. these types implement same interface have unique elements.
i able assign reportable report so:
public class report { private reportable reportable; public void setreportable(reportable reportable){ this.reportable = reportable; } public reportable reportable(){ return reportable; } }
then in client code, able assign reportable instance:
militaryreporter reportable = new militaryreporter(); reportable.setuniqueattribute(some_val); report.setreportable(reportable);
but when later access reportable, cannot access of unique methods. can access methods implemented in interface. not compile:
report.reportable.uniqueattribute();
the problem don't want set reportable's data type militaryreport. want data type reportable, can assign type of reportable it. @ same time, want access unique methods of reportables.
how can around limitation? design pattern?
the whole idea of interface don't care type of reportable is. when declare @ interface level, reportable
instead of militaryreportable
, see methods declared on reportable
. if don't want declare militaryreportable
, know that's is, can cast it:
((militaryreportable)report.reportable).someuniquemethod()
Comments
Post a Comment