Hi All,
I have just started learning about inner classes. To observe the effect of inner classes I tried to run the following application taken from a book. It compiled fine but gave a huge runtime error. The program is as below:
class InnerTest{
public static void main(
String[] args){
Outer o = new Outer();
Outer.Inner i = o.new Inner();//one way
i.seeOuter();
i = new Outer().new Inner();//another way
i.seeOuter();
}
}
public class Outer{
private String s = "outer s";
void makeAndSeeInner(){
System.out.println(this);//refers to Outer.this
Inner i = new Inner();//No need of Outer.this explicitly, because, Outer.this already exists here.
i.seeOuter();
}
void seeInner(){
System.out.println(s);//How to see Inner s here? You can't, because Inner.this not present.
}
strictfp class Inner{
private String s = "inner s";
void seeOuter(){
System.out.println(this);
System.out.println(Outer.this.s);//Need to mention Outer because this refers to Inner.this here.
System.out.println(s);//Or, this.s
}
}
abstract class AbInner{
private String s = "abstract inner s";
void seeOuter(){
System.out.println(this);//this refers to the subclass not the abstract class.
System.out.println(Outer.this.s);
System.out.println(s);
}
abstract void abMethod();
}
class Some extends AbInner implements Runnable, Animal{//can extend and implement
public void run(){}
void abMethod(){
System.out.println(this);
System.out.println(super.s);
}
}
public static void main(String[] args){
Inner i = new Outer().new Inner();
//Inner i = new Inner();//can't exist w/o outer class instance
i.seeOuter();
Outer o = new Outer();
o.makeAndSeeInner();
o.seeInner();
//new Outer().makeAndSeeInner();
Some so = new Outer().new Some();
so.seeOuter();
so.abMethod();
}
}
interface Animal{
}
The runtime exception that i received was: Exception in
thread "main" NoClassDefFoundException : Outer
caused by java.lang.ClassNotFoundException : Outer
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrevileged(Native Method)
at java.lang.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
I got similar runtime exception for other two Inner Class Apps also that i tried to run.Please Help!!!
Regards,
Rekha