java - Why I cannot instantiate this variable? -
i have piece of code on 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 don't remove comment on first line said (about pageapp) "cannot find symbol"... why this? if-else instantiate it, in case. wrong? cheers
actually, have should not compile since pageapp
not within scope on last line. looks confused between variable declaration , variable assignment. java allows both in same statement, however, may declare variable 1 time within same scope.
if uncomment first declaration still leave others inside if
, else
statements, compile time errors related duplicate declaration. within if
, else
statement blocks declaring same variable different types. should find, if possible, abstract type variable shared 2 types instantiating (e.g. mainhomepage
, mainaffittaappartamenti
) , declare outside if
, else
blocks , in main method scope.
for example, if mainaffittaappartamenti
sub-class mainhomepage
can this:
mainhomepage pageapp; // declare here not assign string pagevalue=request.getparameter("page"); if((pagevalue!=null) && (pagevalue.compareto("1")==0)) { pageapp = new mainhomepage(session); } else if((pagevalue!=null) && (pagevalue.compareto("2")==0)) { pageapp = new mainaffittaappartamenti(session); } else { pageapp = new mainhomepage(session); } pageapp.somemethod();
notice in inner blocks did not declare variable again (that define it's type). since, given assumption statement, mainaffittaappartamenti
sub-class of mainhomepage
assignment of pageapp
valid still.
Comments
Post a Comment