package 内部类;
public class Test{
public static void main(String[] args){
// 初始化Bean1,成员内部类
Test test = new Test();
Test.Bean1 bean1 = test.new Bean1();
bean1.I++;
// 初始化Bean2,静态内部类
Test.Bean2 bean2 = new Test.Bean2();
bean2.J++;
//初始化Bean3
Bean.Bean3 bean3 = new Bean().new Bean3();
bean3.k++;
}
class Bean1{
public int I = 0;
}
static class Bean2{
public int J = 0;
}
}
class Bean{
class Bean3{
public int k = 0;
}
}
###//创建静态内部类对象的一般形式为: 外部类类名.内部类类名 xxx = new 外部类类名.内部类类名()
###//创建成员内部类对象的一般形式为: 外部类类名.内部类类名 xxx = 外部类对象名.new 内部类类名()
public class Test {
public static void main(String[] args) {
Outter outter = new Outter();
outter.new Inner().print();
}
}
class Outter
{
private int a = 1;
class Inner {
private int a = 2;
public void print() {
int a = 3;
System.out.println("局部变量:" + a);
System.out.println("内部类变量:" + this.a);
System.out.println("外部类变量:" + Outter.this.a);
}
}
}
//321
//1)成员内部类的引用方式必须为 Outter.Inner.
//
//2)构造器中必须有指向外部类对象的引用,并通过这个引用调用super()
class WithInner {
class Inner{
}
}
class InheritInner extends WithInner.Inner {
// InheritInner() 是不能通过编译的,一定要加上形参
InheritInner(WithInner wi) {
wi.super(); //必须有这句调用
}
public static void main(String[] args) {
WithInner wi = new WithInner();
InheritInner obj = new InheritInner(wi);
}
}
###//匿名类
//只要一个类是抽象的或是一个接口,那么其子类中的方法都可以使用匿名内部类来实现
//匿名内部类也就是没有名字的内部类
//
//正因为没有名字,所以匿名内部类只能使用一次,它通常用来简化代码编写
//
//但使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口
###//在接口上使用匿名内部类
interface Person {
public void eat();
}
public class Demo {
public static void main(String[] args) {
Person p = new Person() {
public void eat() {
System.out.println("eat something");
}
};
p.eat();
}
}
###//匿名内部类的基本实现
abstract class Person {
public abstract void eat();
}
public class Demo {
public static void main(String[] args) {
Person p = new Person() {
public void eat() {
System.out.println("eat something");
}
};
p.eat();
}
}
###//Thread类的匿名内部类实现
public class Demo {
public static void main(String[] args) {
Thread t = new Thread() {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}
}
};
t.start();
}
}
JavaSE阶段2_内部类
最新推荐文章于 2022-12-19 15:52:09 发布