Get started with java-8.9 Nested classes (using static internal classes)
In this section, we will discuss Nested classes.
1. Concept
When internal classes use static, they are nested classes.
package com.ray.ch07;public class Test {private static class MyTest3{}}
MyTest3 is a nested class.
2. Notes
(1) It can only communicate with the static part of the external class.
(2) static features can be directly used instead of reference to external class objects.
package com.ray.ch07;public class Test {private int id = 1;private static String name = aaa;private static class MyTest1 {public void say() {// System.out.println(id);//errorSystem.out.println(name);}}private class MyTest2 {public void say() {System.out.println(id);System.out.println(name);}}public static void main(String[] args) {// new Test().new MyTest1();//error.new Test.MyTest1().say();new Test().new MyTest2();}}
From the code above, we can see that MyTest1 cannot access the id, while MyTest2 can.
In addition, we can see that MyTest1 has the static feature and does not need new, but we still need to add a bracket, while MyTest2 needs new to call the method in it.
(3) Nested classes do not have this reference
Because the nested class uses static, this cannot be used to reference external classes.
(4) Use Cases
A common application scenario is to work with the main function.
Because only useful code is published when a project is released, and Code such as testing is not released, this is more useful now.
Let's compare the two groups of codes below the idea:
package com.ray.ch08;public class Test {public static void main(String[] args) {}}
package com.ray.ch08;public class Test {private void say() {System.out.println(abc);}public static class Tester {public static void main(String[] args) {Test test = new Test();test.say();}}}
The functions of the above two sets of code are the same, but the generated files are different.
The first code generates only one Test. class
But the second one will generate two files: Test. class and Test $ Tester. class, we only need to delete the second file at the time of release, then the test code will be deleted, which is more convenient.
Summary: This chapter discusses the concept and points of attention of Nested classes.