Introduction to internal classes
A class defined in another class is called an inner class
Member internal class
1..new To create an internal class of a member, you must first create an instance of the external class, and then create an object of the internal class through .new
2..this You can access all properties and methods of external classes through the class name.this of the external class.
public class Test1 { String name = "asnd"; public static void main(String[] args) { Test1 test1 = new Test1(); Inner mInner = test1.new Inner(); mInner.print(); } void show() { System.out.println("show"); } public class Inner { String name = "123"; private void print(){ show(); System.out.println(name);//Print 123 System.out.println(Test1.this.name);//Print asnd } }}Anonymous internal class
A class without a name will also create an object while creating a class.
You only need to use the class once to use anonymous internal classes
File file = new File("D:/cc.txt") { @Override public boolean delete() { System.out.println("Do not delete y/n"); Scanner input = new Scanner(System.in); String str = input.next(); if (str.equals("y")) { return super.delete(); } System.out.println("Delete failed"); return false; } }; file.delete(); }Anonymous object
The object only needs to be accessed once.
new Thread() { @Override public void run() { System.out.println("Thread start!"); try { Thread.sleep(2000); System.out.println("Thread end!"); } catch (Exception e) { e.printStackTrace(); } super.run(); } }.start();Static inner class
1. Static inner classes can only access static methods and variables of external classes, and cannot access non-static.
2. Static inner classes can be created directly without creating references to external classes.
Anonymous internal class access local variables
Internal class access local variables must be final. If not added, jdk1.8 will be added by default. When the variable used is changed, the following method can be used, or the following i can be set as static at the beginning.
for (int i = 0; i < 5; i++) { final int finali = i; new Thread() { public void run() { System.out.println(finali); }; }.start(); }The following is an introduction to the implementation skills of internal classes
public static void main(String[] args) { Lam mLam = new Lam(); //The first method of implementation mLam.to(new Light() { @Override public void shin() { System.out.println("on's first method"); } }); //The second method of implementation class MyLam implements Light{ @Override public void shin() { System.out.println("second"); }} mLam.to(new MyLam()); }} interface Light { void shin();}class Lam { public void to(Ligh ligh) { ligh.shin(); System.out.println("on"); }}Thank you for reading, I hope it can help you. Thank you for your support for this site!