Tuesday, August 21, 2012

Inner classes in Java

A class inside another class inner or nested class
1. Nested class
2. Method local inner class
3. static inner class
4. Anonymous inner class


Nested Class


public class Outer {
  private String message="welcome to java inner classes";
  private class Inner{
    private String greetings="Hi! how are you?";
    public void display(){
      System.out.println(message);
    }
  }
  public void show(){
    System.out.println(message);
    System.out.println(new Inner().greetings);
  }
}
 
public class Outer {
  private String message="welcome to java inner classes";
  public class Inner{
    private String greetings="Hi! how are you?";
    public void display(){
      System.out.println(message);
    }
  }
  public void show(){
    System.out.println(message);
    System.out.println(new Inner().greetings);
  }
}
 
public class Manager {
  public static void main(String[] args) {
    Outer obj=new Outer();
    obj.show();
    /* Creation of the inner class object */
    Outer.Inner inner=obj.new Inner();
    /* Another way of creation of the inner class */
    Outer.Inner inn=new Outer().new Inner();
    inn.display();
  }
}
 
public interface Game {
  void play();
}
 
public class Car {
  public Game getGame(){
  return new MyGame();
  }

  private class MyGame implements Game{
    @Override
    public void play() {
      System.out.println("The Game is started");
    }
  }
}
 
public class GameMain {
  public static void main(String[] args) {
    Car c=new Car();
    Game g=c.getGame();
    g.play();
  }
}

 

Method local inner classes

class Example{
  public void printMessage(){
    final String greetings="Hi! how are you?";
    class User{
      private String message="Welcome to method local inner class";
      void print(){
        System.out.println(message+" "+greetings);
      }
    }
    User obj=new User();
    obj.print();
  }
}


public class MethodLocalInner {
  public static void main(String[] args) {
    Example obj=new Example();
    obj.printMessage();
  }
}

Static inner classes


class StOuter{
  static class StInner{
    void print(){
      System.out.println("Hello");
    }
  }
}

public class StaticInnerDemo {
  public static void main(String[] args) {
    StOuter.StInner obj=new StOuter.StInner();
    obj.print();
  }
}

Anonymous Inner Classes

interface One{
  void show();
}

public class AnonymousDemo {
  public static void main(String[] args) {
    
    One obj=new One() {
        @Override
        public void show() {
          System.out.println("Welcom to Bangalore");
        }
    };
    obj.show();
  }
}

No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...