1.内部类
package cn.hncu_06;
import cn.hncu_06.Outer.Inter;
/*
* 内部类
* 本类定义在其他类的内部,这个类就是内部类.
* 举例在A 类中定义了一个B类,B类就是内部类
*
* 内部类访问的特点:
* (1) 内部类可以直接访问外部类的成员,包含私有.
* 内部类的分类:
* 局部内部类:在方法体类或方法参数位置定义的内部类
* 成员内部类::在成员位置(类中方法外)定义的内部类
* 创建成员内部类对象的格式:
* 外部类名.内部类名 对象名 = 外部类对象.内部类对象;
*
*/
class Outer {
private int a=10;
//成员内部类
class Inter {
int num = 100;
public void method(){
System.out.println(a);
}
}
public void function(){
Inter inter = new Inter();
System.out.println(inter.num);
}
public void fun(){
//局部内部类
class Inner2 {
int b = 10;
}
Inner2 inter2 = new Inner2();
System.out.println(inter2.b);
}
}
public class Demo {
public static void main(String[] args) {
//我要访问Inter的method方法
//Inter i = new Inter();
//外部类名.内部类名 对象名 = 外部类对象.内部类对象;
Outer.Inter oi = new Outer().new Inter();
oi.method();
//需求:我要调用Outer的fun()
Outer o = new Outer();
o.fun();
}
}
2. 匿名内部类
package cn.hncu_07;
/*
* 匿名内部类
* 是内部类的简化写法.
*
* 前提:存在一个类或接口.
*
* 格式:
* new 类名或接口名(){}
*
* 匿名内部类的本质:
* 是一个继承了该类或者实现了该接口的子类匿名的对象.
*
*/
interface inter {
public void show1();
public void show2();
public void show3();
}
public class Demo {
public static void main(String[] args) {
// new 类名或接口名(){}
// 这就是一个匿名内部类
/*new inter() {
@Override
public void show1() {
System.out.println("show1");
}
@Override
public void show2() {
System.out.println("show2");
}
}.show1();
new inter() {
@Override
public void show1() {
System.out.println("show1");
}
@Override
public void show2() {
System.out.println("show2");
}
}.show2();*/
inter i = new inter() {
@Override
public void show3() {
System.out.println("show3");
}
@Override
public void show2() {
System.out.println("show2");
}
@Override
public void show1() {
System.out.println("show1");
}
};
i.show1();
i.show2();
i.show3();
}
}
package cn.hncu_08;
/*
* 匿名内部类的应用场景
*
* 如果一个方法的参数是一个接口,实际需要的是该接口的实现类对象.
*/
interface Inter {
public void show();
}
class Test {
public void method(Inter inter){
inter.show();
}
}
/*class InterImpl implements Inter{
@Override
public void show() {
System.out.println("show");
}
}*/
public class Demo {
public static void main(String[] args) {
//需求:我要调用Test类中method方法
Test test = new Test();
//test.method(new InterImpl());
test.method(new Inter() {
public void show() {
System.out.println("show");
}
});
}
}
package cn.hncu_09;
/*
* 面试题:
* 按照要求,补齐代码
interface Inter { void show(); }
class Outer { //补齐代码 }
class Demo {
public static void main(String[] args) {
Outer.method().show();
}
}
要求在控制台输出”HelloWorld”
分析:
1. Outer是类名,能直接调用method方法,说明method方法是静态的.
2. Outer.method()能够调用show方法,说明method方法的返回值是一个对象
*/
interface Inter {
void show();
}
class Outer {
public static Inter method(){
return new Inter() {
@Override
public void show() {
System.out.println("HelloWorld");
}
};
}
}
class Demo {
public static void main(String[] args) {
Outer.method().show();
}
}