java - importing final fields using interface (RIGHT/WRONG) -


this question has answer here:

recently saw in somebody's code implements final class variable fields inside interface ex:

public interface commentschema{   static final string db_table_name = "comment";   ... } 

& had implemented class need these variables this:

public class dbcomment implements commentschema {   // use db_table_name value here ...   ... } 

as know if make instance of dbcomment class because of inheritance aspect, he's gonna able access db_table_name not proper because want use values inside dbcomment methods.

now have several questions:

1) implementation proper & ok ?

2) if it's not, how have declare these variables outside of dbcomment class & make class class see these values. (we don't want use abstract class coz class can extends 1 other class in java)

3) why need use static values & methods exist inside interface ? (when implements interface specific class why need make static seen everywhere?)

4) there specification determine kinds of different declarations java methods, classes, enums, etc ?

by default, field declared inside interface marked public static final if programmer doesn't it. means, field in interface constant , impossible modify.

if don't want functionality (whatever reasons have) better have abstract class instead , mark field protected static final.

public abstract class commentschema{     protected static final string db_table_name = "comment"; } 

still, if want base design interfaces, can have interface without field, abstract class implements interface , adds field. doing this, every class extends abstract class implement interface , have access field:

public interface commentschema {     foo(); }  public abstract class commentschemaabstractimpl implements commentschema {     protected static final string db_table_name = "comment"; }  public class commentschemarealimpl extends commentschemaabstractimpl {     @override     public void foo() {         //do something...         baz(db_table_name);     }     private void baz(string s) {         //fancy code here...     } } 

at last, can forget , create enum handle constants.

public enum tablename {     comment("comment");     private string tablename;     private tablename(string tablename) {         this.tablename = tablename;     } } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -