I have this piece of code on a JSP file :
// MainHomePage pageApp = new MainHomePage(session);
String pageValue=request.getParameter("page");
if((pageValue!=null) && (pageValue.compareTo("1")==0)) {
MainHomePage pageApp = new MainHomePage(session);
} else if((pageValue!=null) && (pageValue.compareTo("2")==0)) {
MainAffittaAppartamenti pageApp = new MainAffittaAppartamenti(session);
} else {
MainHomePage pageApp = new MainHomePage(session);
}
pageApp.someMethod();
if i don’t remove comment on the first line it said (about pageApp) “cannot find symbol”… why this? if-else will instantiate it, in any case. What am I wrong? Cheers
Actually, what you have should not compile since
pageAppis not within scope on the last line. Looks like you are confused between variable declaration and variable assignment. Java allows you to do both in the same statement, however, you may only declare a variable one time within the same scope.If you uncomment the first declaration but still leave the others inside the
ifandelsestatements, then you will get compile time errors related to duplicate declaration. Within theifandelsestatement blocks you are declaring this same variable with different types. You should find, if possible, an abstract type for that variable that is shared by the two types you are instantiating (e.g.MainHomePageandMainAffittaAppartamenti) and then declare it outside theifandelseblocks and in the main method scope.For example, if
MainAffittaAppartamentiis a sub-class toMainHomePagethen you can do this:Notice that in the inner blocks I did not declare the variable again (that is define it with it’s type). Since, given my assumption statement,
MainAffittaAppartamentiis a sub-class ofMainHomePagethen the assignment of that topageAppis valid still.