• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

inner class

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why "in.str" is giving error while the method which uses str variable compiles??
Tejal
public class outerdemo{
private int i=4;
private String str="JAVARANCH";
public static void main(String args[]){
outerdemo od=new outerdemo();
outerdemo.innerdemo in=od.new innerdemo();
System.out.println(in.addall());
//System.out.println(in.str);//gives compiler error:
in.printString();
System.out.println(od.str);
}//end main

private class innerdemo{
public int i=6;
int addall(){
int j=i++;
return j;
}//end addall
void printString(){
System.out.println(str);
}//end printstring
}//end inner

}//end outerdemo
 
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is because when you say in.str you are return the variable str that is in reference object in, which is the inner class. Since in doesn't have a variable str you get an error.
However in the method printString in the innerclass, you are not saying this.str, you are just saying str. So it first looks to see if there is a varable local to the inner class, which there is not, so it looks to the outerclass next.
Try out different versions, make a str class in the innerclass, and it will work, change str to this.str in the printString method, and it will give you the variable not defined error, instead of printing in.str, print od.str and it will work.
Bill
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic