如何访问内部类
非静态内部类:
先在Inner里面定义一个内部类
<span style="font-size:14px;">public class Inner {
int q = 1;
<span style="white-space:pre"> </span>private String name = "vv";
public void track(){
System.out.println("追踪");
}
class A{ <span style="color:#33cc00;">//内部类</span>
int w = 2;
public A(){ <span style="color:#33cc00;">//构造内部类方法</span>
System.out.println("System.out.println("q:"+q+"name:"+name); <span style="color:#33cc00;">//访问外部类属性,包括私有化成员</span>
track(); <span style="color:#33cc00;">//直接调用外部类方法</span>
}
public void dadi(){
System.out.println("打的");
}
}
}</span>
在Demo里面定义主方法
<span style="font-size:14px;">import com.att.Inner.A;
public class Demo {
public static void main(String[] args) {
<span style="color:#33ccff;">//非静态类创建对象----》内部类</span>
Inner inner = new Inner();
A a = inner.new A(); <span style="color:#33cc00;">//内部类创建对象</span>
A a2 = new Inner().new A(); <span style="color:#33cc00;">//通过匿名外部类创建内部类对象</span>
a.dadi(); //访问
}
}
</span>
运行结果
任务
<span style="font-size:14px;"> interface Inter { void show(); }
class Outer {<span style="color:#cc33cc;"> //补齐代码</span> }
class OuterDemo {
public static void main(String[] args) {
Outer.method().show();
}
}
要求在控制台输出”HelloWorld”</span>
实践操作
<span style="font-size:14px;">public class OuterD {
public static void main(String[] args) {
Outer.method().show(); //分解分析
}
}
interface Inter{ //定义接口
void show();
}
class Outer{
<span style="color:#cc33cc;">public static Inter method(){
return new Inter(){
@Override
public void show() {
System.out.println("Hello World");
}
};
}</span>
}</span>
运行结果
静态内部类访问外部类
创建静态内部类
<span style="font-size:14px;"> <strong>static</strong> class B{ <span style="color:#33cc00;">//静态内部类</span>
public B(){
track();
System.out.println("name:"+name);
}
public void explore(){
System.out.println("探索");
}
}</span>
调用变量都要是静态,否则会报错
如果内部类为静态,最好把方法也定义为静态
<span style="font-size:14px;"> private <strong>static</strong> String name = "vv";
public <strong>static</strong> void track(){
System.out.println("追踪");
}</span>
主方法里面创建对象
<span style="font-size:14px;"><strong>Inner.B b = new Inner.B(); </strong><span style="color:#6633ff;"> </span></span><span style="font-size:14px;color: rgb(102, 51, 255);"> </span>