Java lets you declare classes almost anywhere, even inside other classes and methods. In this tutorial we'll take a look at some of the possibilities and why you might want to make use of them. In particular, we'll look at inner classes, static inner classes and local classes.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen. Don't forget to change to HD also if the video appears fuzzy.

Code for this tutorial:

App.java:

publicclassApp{publicstaticvoidmain(String[]args){Robotrobot=newRobot(7);robot.start();// The syntax below will only work if Brain is// declared public. It is quite unusual to do this.// Robot.Brain brain = robot.new Brain();// brain.think();// This is very typical Java syntax, using// a static inner class.Robot.Batterybattery=newRobot.Battery();battery.charge();}}

Robot.java:

publicclassRobot{privateintid;// Non-static nested classes have access to the enclosing// class's instance data. E.g. implement Iterable// http://www.caveofprogramming.com/java/using-iterable-java-collections-framework-video-tutorial-part-11/// Use them to group functionality.privateclassBrain{publicvoidthink(){System.out.println("Robot "+id+" is thinking.");}}// static inner classes do not have access to instance data.// They are really just like "normal" classes, except that they are grouped// within an outer class. Use them for grouping classes together.publicstaticclassBattery{publicvoidcharge(){System.out.println("Battery charging...");}}publicRobot(intid){this.id=id;}publicvoidstart(){System.out.println("Starting robot "+id);// Use Brain. We don't have an instance of brain// until we create one. Instances of brain are // always associated with instances of Robot (the// enclosing class).Brainbrain=newBrain();brain.think();finalStringname="Robert";// Sometimes it's useful to create local classes// within methods. You can use them only within the method.classTemp{publicvoiddoSomething(){System.out.println("ID is: "+id);System.out.println("My name is "+name);}}Temptemp=newTemp();temp.doSomething();}}