views:

70

answers:

5

I want to use the lang variable in my code, and give the value in the if command. Is the below code possible in .jsp page ?

<%
  String language = "EN";
  EN lang;
  if (language.equals("EN")){
    lang = new EN();
  }
  else if (language.equals("FR")){
    lang = new FR();
  }
%>
// html ...
<% out.print(lang.variable1); %>

i got this error :

incompatible types; found: mypackage.FR, required: mypackage.EN

code please ?

+2  A: 

Are classes EN and FR derived from a common interface or abstract class? If yes, you can change EN lang; to <abstractClass> lang;. If not, you can start thinking of refactoring your class. An ugly solution would be to use Object lang;

nanda
no they are a class in a package. u mean that i must define EN and FR as a interface or abstract? can u help me with code pleas ?
ammar
An answer from Jaydeep is good enough
nanda
how can i access the variables inside the EN or FR class. Jaydeep code gives back the interface variables value.
ammar
A: 
 lang = new FR();     

It should be

 lang = new ER();     //in else if

here you are assigning an Object of FR to the reference of ER.

I would like to know what is the relationship between FR and ER ?

org.life.java
+1  A: 

lang = new FR();

You are assigning an object of type FR to lang which is of type EN and is clearly wrong.

johnbk
+2  A: 

Your code should look something like this:

interface Lang {

}

class EN implements Lang {

}

class FR implements Lang {

}

<%
  String language = "EN";
  Lang lang;
  if (language.equals("EN")){
    lang = new EN();
  }
  else if (language.equals("FR")){
    lang = new FR();
  }
%>
Jaydeep
how can i access the variables inside the EN or FR class ?
ammar
your another question has my answer http://stackoverflow.com/questions/3759950/professional-usage-of-abstract-class-for-translation/3760265#3760265
Jaydeep
A: 

Instead of declaring lang as EN, declare it as an instance of the superclass of EN and FR (perhaps Lang ?)

Grodriguez