非静态、静态内部类
提供更好的封装,只能让外部类直接访问,不允许同一个包中的其它类直接访问;
内部类可以直接访问外部类的私有属性,内部类被当成其外部类的成员,外部类不能访问内部类的内部属性;
package com.bhzt.innertest;
/**
* 身体
*/
public class body {
private String color="yellow";
/**
* 非静态内部类
* 头
*/
class head{
private String eyes="炯炯有神";
public void getInfo(){
System.out.println("这个人的皮肤是"+body.this.color+",眼睛"+eyes);
}
}
/**
* 静态内部类
*/
static class leg{
}
}
匿名内部类
package com.bhzt.innertest;
/**
* 动物接口
*/
public interface Animal {
void shout();
}
package com.bhzt.innertest;
/**
* 狗
*/
public class Dog {
public void shout(Animal a)
{
a.shout();
}
}
```javascript
package com.bhzt.test;
import com.bhzt.innertest.Animal;
import com.bhzt.innertest.Dog;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class InnerDogTest {
@Test
void shout() {
Dog d=new Dog();
d.shout(new Animal() {//匿名内部类
@Override
public void shout() {
System.out.println("汪汪汪");
}
});
}
}
局部内部类
方法中的内部类