[Android study notes] JAVA basics - inner classes and anonymous inner classes

Inner class: a class is defined inside a class, and the inner class can use the member variables and member functions of the outer class at will. The method of
generating an inner class: first new an outer class and then .new the outer class, such as:
B is A's inner class, then 
A a = new A();//Generate an external class
A.B b = new A().new B();
or
A.B b = a.new B();
Note that each inner class object is associated with its outer class object. In other words, an object with an inner class must have an outer class object corresponding to it.

Anonymous inner class
1. First, an inner class
2. No name
interface A{
	public void doSomething();
}


class AImpl implements A{
	public void doSomething(){
		System.out.println("doSomething");
	}
}


class B{
	public void fun(A a){
		System.out.println("Fun function of class B");
		a.doSomething();
	}
}


class Test{
	public static void main(String args[])
	{
		AImpl al =new AImpl();
		A a = al;
		B b  = new B();
		b.fun(a);
	}
}
/*******************************************************************/
class Test{
	public static void main(String args[])
	{
		//AImpl al =new AImpl();
		//A a = al;
		B b  = new B();
		b.fun(new A(){
			public void doSomething(){
				System.out.println("Anonymous inner class");
			}
		});
	}
}

By Urien April 13, 2018 22:39:45



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325858905&siteId=291194637