当前位置: 移动技术网 > IT编程>开发语言>Java > 什么是实例内部类 Instance inner class有什么语法?

什么是实例内部类 Instance inner class有什么语法?

2018年09月24日  | 移动技术网IT编程  | 我要评论

1.instance inner class定义,用途和用法  

重要语法:马克-to-win:1)实例内部类一定得有个外层类的实例和它绑定在一起,所以可以用this指针。所以必须先实例化外层类之后才能再实例化内部类。(生活中的例子就是子宫和胚胎(不算试管婴儿!))2)语法规定:实例内部类不能有静态的属性或方法,为什么?因为没有外层类的实例就不应该有实例内部类的任何东西存在,包括内部类的静态属性,但静态属性应该在main方法执行时创建,这样就会产生矛盾,所以规定实例内部类不能有静态的属性或方法。马克-to-win:2)既然每个内部类实例都可以改变他们共同的外层类的静态属性或实例属性,他们成为内部类实例们可以交互的地方。(下例中的shell_x,在不断增长。)

例2.1a:类中有个内部类属性。

class shellmark_to_win {
    int shell_x = 100;//既然每个内部类实例都可以改变这里的外层类静态属性或实例属性,马克-to-win:这里成为内部类实例们可以交互的地方
    static int n;
    core core;
    void visitcore() {
        core = new core();
        core.y=8;
        core.display();
    }
    // 下面是个实例内部类,必须有个外层类实例,才能有这个内部类实例。所以就有了this这个概念。
    class core {
/* 下一句错误,根据语法:马克-to-win:静态的域或方法只能出现在静态类或最外层类上。the field m cannot be declared static; static fields can only be declared in static inner class or top level classes,*/     
  //    static int m=9;
        int y = 10; // y is local to core
        void display() {
            shell_x=shell_x+20;
            n=n+1;//轻松访问外层类的静态变量
            system.out.println("n is "+n+" display: shell_x and y " + shell_x + " "+shellmark_to_win.this.shell_x+ " " + y+ " "+this.y);
        }
    }
    core newc()
    {
        return new core();
    }
    void showy() {
        // y=9; // 错误,马克-to-win:外层类不能直接访问内部类的属性。error,y not known here! system.out.println(y);
    }
}
public class test {
    public static void main(string args[]) {
        shellmark_to_win shell = new shellmark_to_win();
        shell.visitcore();
        shellmark_to_win.core sc=shell.new core();//内部类实例是存在于外部对象里的。
        sc.display();
        shellmark_to_win.core sc1=shell.newc();

。。。。。。。。。。。。。。。。。
详情请进:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网