Inner classes problem
Alright in this book i was reading it said that inner classes can directly access the outer class's instance variables...but when i run this it says
"
C:\Documents and Settings\Divinity At Its Best\Desktop\java demystif
c *.java
Demo.java:18: cannot find symbol
symbol : variable student
location: class Inner
System.out.println("Student number is " + student);
"
class Demo{
publicstaticvoid main (String args[]){
Outer outer =new Outer();
outer.display();
}
}
class Outer{
int student = 12345;
void display(){
Inner inner =new Inner();
inner.print();
}
}
class Inner{
void print(){
System.out.println("Student number is " + student);
}
}
Why cant it find the variable....the book makes it seem like inner classes dont need to declare or referance at all...
try this instead:
class Demo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.display();
}
}
class Outer
{
private int student = 12345;
void display()
{
Inner inner = new Inner();
inner.print();
}
// } // get rid of this brace
class Inner
{
void print()
{
System.out.println("Student number is " + student);
}
}
} // and add this one here
> Is it possible to do this in seperate java files?...like if i had Demo.java, Inner.java,
> and Outer.java?
If Inner is to be an inner class then, as was said before, it is declared inside Outer. Clearly it must be part of the same source file.
Your original post referred to the fact that "inner classes can directly access the outer class's instance variables". This is true, but inner classes are not principally a mechanism for allowing access to one class from another. For that we use access modifiers (public/protected/etc) usually as part of the declaration of a method (getStudent()).
Perhaps you can say what you are trying to do: but as regards how, inner classes must be in the same source file as their enclosing class.