Showing posts with label static nested classes. Show all posts
Showing posts with label static nested classes. Show all posts

Monday, 10 February 2014

Inner Class

Non static nested classes are called inner classes

Syntax
    class OuterClass {
        ...
        class InnerClass {
            ...
        }
    }

How to create an object to the inner class
    OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Example
class Outer{
 void print(){
  System.out.println("I am in outer class");
 }

 class Inner{
  void print(){
   System.out.println("I am in Inner class");
  }
 }

 public static void main(String args[]){
  Outer outerObj = new Outer();
  Outer.Inner obj = outerObj.new Inner();
  obj.print();
 }
}

Output
I am in Inner class


There are two additional types of inner classes.

Those are:
    1. Local Classes

Some points to Remember
1. Inner class is associated with an instance, it cannot define any static members itself. Defining static variable inside inner class causes the compiler error
class Outer{
 class Nested{
  static int a = 100;
 }
}
When you tries to compile the above program, compiler throws the below error
Outer.java:3: error: Illegal static declaration in inner class Outer.Nested
           static int a = 100;
           ^
modifier 'static' is only allowed in constant variable declarations
1 error
      

2. You can define static constants in the inner class, but not static variables.
class Outer{
 class Nested{
  static final int a = 100;
 }
}
    3. Defining static methods inside inner class causes compiler error
    class Outer{
     class Nested{
      static void print(){
      }
     }
    }
    
    When you tries to compile the above program, compiler throws the below error
    Outer.java:3: error: Illegal static declaration in inner class Outer.Nested
             static void print(){
             ^
    modifier 'static' is only allowed in constant variable declarations
    1 error
    
         
    4. An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance
    Example
    class Outer{
     String name;
    
     void setName(String name){
      this.name = name;
     }
    
     class Inner{
      public void print(){
       System.out.println(this.name);
       System.out.println(Outer.this.name);
      }
    
      String name;
           
      void setName(String name){
       this.name = name;
      }
    
      public String toString(){
       return name;
      }
     }
    
     public static void main(String args[]){
      Outer obj = new Outer();
      obj.setName("Outer Class Object");
      Outer.Inner in = obj.new Inner();
      in.setName("Inner Class Object");
      in.print();
     }
    }
    
            
    Output
    Inner Class Object
    Outer Class Object
    


    Static Nested Classes                                                 Local Classes                                                 Home

    static Nested classes

    A Nested class with static modifier is called static nested class

        Syntax
        class OuterClass {
            static class StaticNestedClass {
            }
        }

    Just like static methods, a static class, can't access instance properties and instance methods directly. To access them static nested class should create an object for the outer class.

    How To Create an Object for static nested class
        Syntax
        OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

    With an example, we can easily grasp the use of nested classes.

    Consider the following requirement

    Requirement: I want to maintain a database for an university, like How Many colleges are there, How many faculties, How many Students across the university.

    See the below solution, developed using static nested classes.
    class College{
     private String collegeName;
     private int maleFaculty, femaleFaculty, noOfFaculty;
     private int maleStudents, femaleStudents,noOFStudents;
    
     private static class Faculty{
      private static int totalNoOfFaculty;
      private static int totalMaleFaculty;
      private static int totalFemaleFaculty;
     }
    
     private static class Student{
      private static int totalNoOFStudents;
      private static int totalMaleStudents;
      private static int totalFemaleStudents;
     }
    
     private static class CollegeCount{
      private static int totalColleges;
     }
    
     void setFaculty(int totalMale, int totalFemale){
      maleFaculty = totalMale;
      femaleFaculty = totalFemale;
      noOfFaculty = totalMale+totalFemale;
        
      Faculty.totalNoOfFaculty = Faculty.totalNoOfFaculty + noOfFaculty;
      Faculty.totalMaleFaculty = Faculty.totalMaleFaculty + maleFaculty;
      Faculty.totalFemaleFaculty = Faculty.totalFemaleFaculty + femaleFaculty;
     }
    
     void setStudents(int totalMale, int totalFemale){
      maleStudents = totalMale;
      femaleStudents = totalFemale;
      noOFStudents = totalMale+totalFemale;
    
      Student.totalNoOFStudents = Student.totalNoOFStudents + noOFStudents;
      Student.totalMaleStudents = Student.totalMaleStudents + maleStudents;
      Student.totalFemaleStudents = Student.totalFemaleStudents + femaleStudents;
     } 
    
     College(String collegeName){
      this.collegeName = collegeName;
      CollegeCount.totalColleges++;
     }
    
     static void printConsolodateData(){
      System.out.println("Total Colleges " +CollegeCount.totalColleges);
      System.out.println("Total Faculties " + Faculty.totalNoOfFaculty);
      System.out.println("Total Male Faculties " + Faculty.totalMaleFaculty);
      System.out.println("Total Female Faculties " + Faculty.totalFemaleFaculty);
      System.out.println("Total Students " + Student.totalNoOFStudents);
      System.out.println("Total Male Students " + Student.totalMaleStudents);
      System.out.println("Total Female Students " + Student.totalFemaleStudents);
     }
    }
    

    As You see in the above program, class College contains 3 static nested classes Faculty, Student, CollegeCount.

    Faculty class
    Has 3 static variables to count total number of faculties, total number of male faculties and total number of femal faculties.

    Student Class
    Has 3 static variables t count total number of students, total number of male students, total number of female students.

    CollegeCount class
    Contains a variable to count total number of colleges.
    class CollegeTest{
     public static void main(String args[]){
      College c1 = new College("SSIET");
      College c2 = new College("UCEK");
      
      c1.setFaculty(70, 30);
      c1.setStudents(1000, 700);
      c1.setFaculty(100, 70);
      c1.setStudents(2000, 1500);
      
      College.printConsolodateData();
     }
    }
    
     
    Output
    Total Colleges 2
    Total Faculties 270
    Total Male Faculties 170
    Total Female Faculties 100
    Total Students 5200
    Total Male Students 3000
    Total Female Students 2200
    


    Some Points to Remember
    1. You can't access non static fields from static nested class directly
         Example
    class Outer{
     String name = "Outer class";
     
     static class Nested{
      public void print(){
       System.out.println(name);
      }
     }
    }
    

    When you try to compile the above program, compiler throws below error      
    Outer.java:5: error: non-static variable name cannot be referenced from a static context
    System.out.println(name);
    ^
    1 error
    
         
    2. You can't access non static methods from static nested class directly
         Example
    class Outer{
     void outerMethod(){
     }
    
     static class Nested{
      public void print(){
       outerMethod();
      }
     }
    }
    
              
    When you try to compile the above program, compiler throws below error
    Outer.java:8: error: non-static method outerMethod() cannot be referenced from a static context
    outerMethod();
    ^
    1 error
    

    3. To access non static fields, methods from static nested class, object for the outer class should be created.    
    class Outer{
     void outerMethod(){
     }
    
     static class Nested{
      Outer obj = new Outer();
      public void print(){
       obj.outerMethod();
      }
     }
    }
    


    Nested Classes                                                 Inner Class                                                 Home

    Nested Classes

    Java provides a facility like, you can define a class inside other class. This feature is called Nested classes.

        Example
        class OuterClass {
            class NestedClass {

            }
        }

    Nested Classes can be static or non-static. A Nested class can be private, public, protected and default. Non-static nested classes are called inner classes.

        Example
        class OuterClass {   
            static class StaticNestedClass {

            }

            class InnerClass {

            }
        }

    Uses Of Nested classes
    1. Improve Encapsulation : We can make the nested classes as private, so outside world these nested classes are not visible.
    2. More readable code : Making small nested classes and enclosing thse with outer classes, makes the code readable


    final keyword                                                 static nested classes                                                 Home