5

I don't know how to describe my problem, so I will give you a quick explanation.

I want to make a program where the user can choose a language and then the text afterwards is printed in that given language. Currently I am 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 that I am able to use language.anyMethod(); that is given by the user's choice. AFAIK you cannot override fields, so I was thinking about packing all fields in abstract methods (in the superclass) that only return the value and overriding those.

 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 the getter-methods or did I just miss something I don't know about? Would be nice if you want to help out.

(I am currently just playing around in Java and thought having a language selectable would be quite fun. If you have experiences to share (libraries, properties, ... ? ), feel free to do so) :)

music
  • 51
  • 2
  • Take a look at [this tutorial](http://docs.oracle.com/javase/tutorial/i18n/), specifically the parts about using a `ResourceBundle`. – azurefrog Sep 18 '14 at 21:01
  • Instead of using a lot of methods you could think about using a map with a key like `general.save` and the value is the localization of the string. That way you avoid that methods and you can group your entries. You may also think about using constants defined in a `Language` interface as keys. The same interface could define a method like `String getText(final String key);` that will return the localized text for the used language. Additionally to the language classes and this interface you need something like a `LanguageHandler` class that provied instances of available `Language` instances. – Tom Sep 18 '14 at 21:19

2 Answers2

7

If the issue is really I18N, you should probably look into ResourceBundles, as @azurefrog suggested. Other than that, this is a sound OO design - the base class defines a method (thanks()), and each concrete subclass implements it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
4

I don't see anything wrong that you have done.

You are using all the pillar 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 have a method definition just to override then use interface and not abstract class. There is a difference between both.(Interface vs Abstract Class (general OO))

Community
  • 1
  • 1
StackFlowed
  • 6,664
  • 1
  • 29
  • 45