JAVA ----- inner class

1. Inner class
Definition: A class or interface is defined in another class or interface ; you can also think of an interface as a special class.
Code implementation definition:

// An highlighted block
public class A1{
    
    //外部类
    class B1{
    
    }//内部类
    interface C1{
    
    }//内部接口
  }

~ Classes other than internal classes are called external classes;
~ The name of an internal class must be distinguished from the external class in which it is located, and there is no requirement between it and other classes;
some are shown below 内联代码片.

// An highlighted block
//内部类的全名叫做[外部类名称$内部类名称]
public class A1 {
    
    
public class A1{
    
    } //语法报错
class B1{
    
    } //语法正确,默认编译的结果名称为A1$B1.class
}
class B1{
    
    }

~ The inner class can access all the variables and methods of its outer class.
Here are some 内联代码片.

// An highlighted block
public class A1 {
    
    //外部类的范围限定词只能是public或者默认package
	private String name;public class B1 {
    
     //内部类的范围限定词可以是4种
	public void pp() {
    
    
		System.out.println(name); 
		System.out.println(A1.this.name);
		A1.this.name="ffff";// //这里的A1.this用于表示A1类对象
//System.out.println(this.name);报错的原因是this用于指代当前类的对象,当前类B1中并没有属性name
		pp(); 
		A1.this.pp();
		}
	}
	private void pp(){
    
    }
}

~ The external class cannot directly access the implementation details of the internal class, and can be directly accessed by creating the internal class object, without being affected by the qualifier. Show some below 内联代码片.

// A code block
public class A1 {
	private String name;
	public class B1 {
		private int age=99;
			public void ff();				
				System.out.println(name);
				System.out.println(A1.this.name);
				A1.this.name="ffff";
				}
				private void dd(){}
				}
				private void pp(){
				B1 b=new B1(); //如果需要在外部类中访问内部类的实现细节则需要构建内部类对象,然后通过内部类对象进行访问
				b.ff();
				System.out.println(b.age); //注意:可以直接访问内部类中的私有属性b.dd();//私有方法仍旧可以直接调用
				}
		}

~ Internal analogs have three more private/protected/static modifiers than external classes. These three modifiers cannot be used on external classes;

~ Non-static inner classes cannot have static members, while static inner classes do not have this restriction;

Show some below 内联代码片.

// An highlighted block
public class A{
    
    
	protected class B1 {
    
    
		private int age = 99;
		{
    
     }
		//允许包含非静态代码块
		private static String password="123456";//非静态内部类中不能包含静态属性
		static{
    
     }//非静态内部类中不允许包含静态代码块
		public B1() {
    
    //允许定义构造器和析构器方法
		}
		public static void hh(){
    
    } //非静态内部类中不允许包含静态方法
	   }
}

Guess you like

Origin blog.csdn.net/weixin_42437438/article/details/112910636