1. Concept
In Java, a class is defined inside another class, or inside a method. Such a class is called an internal class. The inner class can freely access any member of the outer class, but on the contrary, the outer class cannot freely access the members of the inner class. The inner class needs to be instantiated before it can be called.
2. Access rules
(1) You can directly access members of the external class , including private
(2) If an external class wants to access internal class members, it must create an object
3. Classification
(1) Internal member Class
(2) Local inner class
(3) Static inner class
(4) Anonymous inner class
4.Instance
public class Product1 { class Design{ private String name = "P30 pro"; public String showName() { return name; } } class Content{ private int i; Content(int value){ i = value; } int value() {return i;} } public void show(int value) { Content c = new Content(value); Design d = new Design(); System.out.println(d.showName()); System.out.println(c.value()); } public static void main(String[] args) { Product1 p = new Product1(); p.show(6000); } }
This example shows the most basic usage of inner classes, which is to place the definition of one or more classes inside the periphery. You can see that the use in the show() method is the same as that of ordinary classes, there is no difference.
The above is the detailed content of What are the access rules for inner classes in java. For more information, please follow other related articles on the PHP Chinese website!