Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use abstract methods instead of fields

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) :)

like image 873
music Avatar asked Sep 18 '14 20:09

music


2 Answers

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.

like image 86
Mureinik Avatar answered Oct 18 '22 05:10

Mureinik


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))

like image 23
StackFlowed Avatar answered Oct 18 '22 07:10

StackFlowed