Use abstract methods instead of fields

I do not know how to describe my problem, so I will give you a brief explanation.

I want to create a program in which the user can select a language, and then the text will be printed in that language. I am currently thinking of something like this:

// Super | class Language; // Sub | --- class German; // Sub | --- class English; if(UserChoseEnglish()) language = new English(); else language = new German(); 

English and German have the same public static final fields, so I can use language.anyMethod(); which is set by the user’s choice. AFAIK, you cannot redefine fields, so I thought about packing all the fields in abstract methods (in a superclass) that return only a value and redefine them.

  public abstract class Language { public abstract String thanks(); } public class English extends Language { @Override public String thanks() { return "Thanks!"; } } public class German extends Language { @Override public String thanks() { return "Danke!"; } } 

Is this considered bad practice? Should I just override getter methods or just skip something I don't know about? It would be nice if you would like to help.

(I'm just playing Java now and I think that choosing a language will be quite funny. If you have experience sharing (libraries, properties, ...?), Feel free to do it) :)

+5
source share
2 answers

If the problem is really in I18N, you should probably look into ResourceBundles, as @azurefrog suggested. In addition, this is an OO sound design - the base class defines the method ( thanks() ), and each particular subclass implements it.

+7
source

I do not see anything wrong with what you did.

You use all the basics of object-oriented programming. ( http://standardofnorms.wordpress.com/2012/09/02/4-pillars-of-object-oriented-programming/ )

Just a suggestion, if you just need to define a method definition only for overriding, use an interface, not an abstract class. There is a difference between the two. ( Interface versus abstract class (generic OO) )

+4
source

Source: https://habr.com/ru/post/1202909/


All Articles