Day 28 : Inner class

Chi-Tse Chiang
2022-10-13 23:41:38

Intro

Internal classes are generally referred to as nested classes.

As the name suggests, a class or interface has a class inside it.

The main purpose is to group classes together. Why do we need this?

1. Improve the readability and maintainability of the code

2. Internal classes have access to the elements of external classes, which optimizes the requirements of the code

Syntax for declaring internal classes:

class Outer_Class{
	//OuterClass members
	class Inner_Class{
		//InnerClass members
	}
}

Class

The internal categories are divided into four main types, each with different functions in mind:

Member inner class

Define another category within a category

Anonymous inner class

Without declaring a class name, use new to generate an object.

Local inner class

Things inside the area are only used within the function.

Static Inner Class

Directly declare internal class objects without creating external class objects.

The following is a comparison of the differences between the general and static inner class.

Inner Class

class Outer_Class {
  int num = 12;

  class Inner_Class {
    int num2 = 6;
  }
}

When we want to call an internal member within a general internal category, we first create an object externally and access the internal through this.

Outer_Class Outer = new Outer_Class();

/*Outer_name.Inner_name Inner_objname = Outer_objname.new Inner_name()*/
Outer_Class.Inner_Class Inner = Outer.new Inner_Class();

public class Main {
  public static void main(String[] args) {
	  Outer_Class Outer = new Outer_Class();
	  Outer_Class.Inner_Class Inner = Outer.new Inner_Class();

      System.out.println(Outer.num * Inner.num2);
  }
}

In addition to accessing internal members from outside the object, we can also access external data from within.

class Outer_Class {
  int num = 12;

  class Inner_Class {
	  public int Inner_Function(){
			return num;
	  }
  }
}

public class Main {
  public static void main(String[] args) {
	  Outer_Class Outer = new Outer_Class();
	  Outer_Class.Inner_Class Inner = Outer.new Inner_Class();

      System.out.println(Inner.Inner_Function());
  }
}

Internal classes can access variable functions of external classes; object instantiation of internal classes via external classes

Static Inner Class

Static internal classes As with the static functions mentioned earlier, here you do not need to create objects via an external class to access internal members.

class Outer_Class {
  int num = 12;

  static class Inner_Class {
    int num2 = 6;
  }
}

public class Main {
  public static void main(String[] args) {
	Outer_Class.Inner_Class Inner = new Outer_Class.Inner_Class();

    System.out.println(Inner.num2);
  }
}