Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 42 Inner Clases
- //---------------------------------------------------------------------------------------------------------------------------------------
- //App.java
- public class App {
- public static void main(String[] args) {
- Robot robot= new Robot(7);
- robot.start();
- Robot.Battery battery = new Robot.Battery();
- battery.charge();
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- //Robot.java
- public class Robot {
- private int id;
- //Non Static Inner Class
- private class Brain { //inner class
- public void think(){
- System.out.println("Robot " + id + " is thinking. ");
- }
- }
- //Second Type of Inner Class: Static Inner Class
- /* 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.
- */
- public static class Battery {
- public void charge(){
- System.out.println("Battery charging...");
- }
- }
- public Robot(int id) { //rightclick>source>generate constructor using id>delete "super();" because its not needed
- this.id = id;
- }
- public void start(){
- 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).
- Brain brain = new Brain();
- brain.think();
- // Sometimes it's useful to create local classes
- // within methods. You can use them only within the method.
- final String name = "Robert";
- class Temp {
- public void doSomething() {
- System.out.println("ID is: " + id);
- System.out.println("My name is " + name);
- }
- }
- Temp temp = new Temp();
- temp.doSomething();
- }
- }
- //---------------------------------------------------------------------------------------------------------------------------------------
- /* Run Results:
- Robot 7 is thinking.
- ID is: 7
- My name is Robert
- Battery charging...
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement