------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
内部类:
内部类的访问规则:
1.内部类可以直接访问外部类中的成员,包括私有
之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式: 外部类名.this
2.外部类要访问内部类,必须建立内部类对象。
class outer{
int num = 5;
class inner{
System.out.println("num="+num);//可以直接调用外部成员
}
void method(){
inner in = new inner();//创建内部类的对象
show();//调用内部类的方法
}
}访问格式:class Body{
private class zhangcheng//内部类
{
}
public void show()
{
new zhangcheng();//必须建立对象
}
}
class Outer
{
private static int x = 3;
static class Inner
{
static void function(){
System.out.println("inner:"+x);
}
}
static class Inner2{
void show(){
System.out.println("inner2 show");
}
}
public static void method(){
new Inner2().show();
}
}
class InnerClassDemo2
{
public static void main(String args[]){
Outer.Inner.function();
new Outer.inner().function();//直接访问内部类中的成员
Outer.Inner in = new Outer().new Inner();//创建内部类对象
in.function();//调用内部类的方法
}
}内部类在定义时:class Outer
{
int x = 3;
void method(final int a){
final int y = 4;
class Inner{
void function(){
System.out.println(y);
}
}
new Inner().function();
}
class InnerClassDemo{
public static void main(String args[]){
Outer out = new Outer();
out.method(7);
out.method(8);
}
}匿名内部类:abstract class AbsDemo{
abstract void show();
}
class outer{
int x = 3;
class Inner extends AbsDemo{
int num = 90;
void show(){
System.out.println('show:"+num);
}
void abc(){
System.out.println("abc");
}
}
public void function(){
AbsDemo d = new AbsDemo(){
int num = 9;
void show(){
System.out.println("num="+num);
}
void abc(){
System.out.println("abcccc");
}
};//注意这个分号
d.show();//ok,实现了接口
d.abc();//error,自定义方法,没有实现接口或者是继承一个类,抽象类不能继承,只能实现
}
}
class InnerclassDemo{
public static void main(String args[]){
new Outer().function();
}
}
interface Inter{
void method();
}
class test{
static class Inner implements Inter
{
public void method()
{
System.out.println("method run");
}
}
static Inter function(){
return new Inter(){
public void method(){
System.out.println("method run");
}
}; }
}
class Innerclasstest
{
public static void main(String args[]){
//test.function():test类中有一个静态方法function
//method():function这个方法运算后的解惑是一个对象,而且是一个Inner类型的对象
//因为只有是Inter类型的对象,才可以调用method方法
test.function().method();
inter in = test.function();
in.method();
show(new Inter()
{
public void method()
{
System.out.println("method show run");
}
});
}
public static void show(Inter in)
{
in.method();
}
}
class Innertest
{
public static void main(String args[]){
new object()
{
public static function()
{
}
}.function();
}
}
原文地址:http://blog.csdn.net/orangeisnotapple/article/details/41757663