public class Out{
class In{ //此时In就是内部类
}
}
//外部类
class Outter {
// 实例内部类:没有使用static修饰
class Inner {
}
}
public class InnerDemo1 {
public static void main(String[] args) {
// 创建实例内部类,没有使用static修饰,属于外部类的对象,因此,创建实例内部类前,必须存在外部类对象
Outter out = new Outter();
// 通过外部类对象创建内部类对象
Outter.Inner in = out.new Inner();
}
}
//外部类
class Outter {
private String name = "out";
private Integer age = 17;
// 实例内部类:没有使用static修饰
class Inner {
private Integer age = 18; // 隐藏现象,隐藏了外部类的age
Inner() {
// 特点:1.实例内部类能直接访问外部类成员
// 2.当实例内部类和外部类有同名的字段或者方法时,会发生隐藏现象
System.out.println(name + this.age);// 输出out18
// 此时若需要使用外部类的age,语法:外部类.this.age
System.out.println(Outter.this.age);// 输出17
}
}
}
//外部类
class Outter {
// 静态内部类:使用static修饰
static class Inner {
}
}
public class InnerDemo2 {
public static void main(String[] args) {
// 因为静态内部类属于外部类本身,可以直接通过外部类类名来访问(类比字段)
Outter.Inner in = new Outter.Inner();
}
}
//外部类
class Outter {
static String name = "outter";
public Integer age = 17;
// 静态内部类:使用static修饰
static class Inner {
Inner() {
// 静态内部类能直接访问外部类的静态成员
System.out.println(name);// 输出 outter
// 访问外部类的实例成员,必须通过外部类的实例去访问.
System.out.println(new Outter().age);// 输出 17
}
}
}
public class InnerDemo3 {
public static void main(String[] args) {
// 局部内部类
class Inner {
}
}
}
public class InnerDemo3 {
public static void main(String[] args) {
int age = 17;
final int num = 15;
// 局部内部类
class Inner {
public void test() {
// 报错:Cannot refer to a non-final variable age inside an inner class defined in a different method
System.out.println(age);
System.out.println(num);// 正确
}
}
}
}
//定义一个接口
interface Person {
public void eat();
}
public class AnonymousDemo {
public static void main(String[] args) {
// 使用匿名内部类
Person p = new Person() {
public void eat() {
System.out.println("eat something");
}
};
p.eat();
}
}
public class Outer {
public void someOuterMethod() {
// Line 3
}
public class Inner {
}
public static void main(String[] argv) {
Outer o = new Outer();
// Line 8
}
}
/*
* Which instantiates an instance of Inner?
A. new Inner(); // At line 3
B. new Inner(); // At line 8
C. new o.Inner(); // At line 8
D. new Outer.Inner(); // At line 8
*/
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有