Java – how to avoid code duplication of many small classes?
I have different courses, including English, Spanish, French, etc
Class English{ String name = "English"; String alias = "ENG"; } Class French{ String name = "French"; String alias = "Fre"; }
Similar to other languages
There is also a class called language:
Class Language{ String name = ""; String alias = ""; }
According to my request, I want to put English / French / Spanish into my language course
Class ABC{ main(){ Language lan = new Language(); Object obj = getObject(1); if(obj instanceof English){ lan.name = ((English)obj).name; lan.aliasName = ((English)obj).aliasName; } } }
If I have 10 languages, do I need to write the same code for 10 different languages? In this case, how do I make a single method and pass these parameters as parameters? Something like this:
setVariablesForLanguage(String className,Object obj)
Here I only show 2 variables, but my class will contain more than 100 variables My actual requirement is that I set my language variables from one of the languages
Solution
If you want to make several subclasses, each with a constant value, you shouldn't make them classes I suggest making them constant instances of the language:
public static final Language ENGLISH = new Language("English","Eng"); public static final Language FRENCH = new Language("French","Fre");
And provide a matching constructor for language (actually, it looks more like enum, but I won't pour too much on you right away.)
Then in your main code, don't check whether it is an example of English, French, etc Just check whether it is a language, and then call it.
Language lan = new Language(); Object obj = getObject(1); if(obj instanceof Language){ lan.name = ((Language)obj).name; lan.aliasName = ((Language)obj).aliasName; }