Java 类的内部嵌套子类型定义 如何正确饮用
发布日期:2021-05-07 23:35:37 浏览次数:21 分类:原创文章

本文共 900 字,大约阅读时间需要 3 分钟。

写了一个非常简单的例子


public class test {    public class abc {    }    public static void main (String[] args) {        ...    }}

在main函数中 申明abc的对象

abc var = new abc();

编译的时候总是报告这个错误

test.java:7: non-static variable this cannot be referenced from a static context

        abc var = new abc();

                  ^

1 error


shell returned 1


Press ENTER or type command to continue


调查类一下StackOverflow 上面有如下解释

http://stackoverflow.com/questions/15331846/non-static-variable-this-cannot-be-referenced-from-a-static-context

In Java there are : "Static nested class" and . Without the static keyword it is an inner class and you will need an instance of ShowBike to access ShowBike.Bycicle:

大概意思就是java的嵌套类型有两种一个事静态的一个是非静态的。因为main函数是静态的所以需要调用静态的内嵌子类。如果一定要吊用非静态的子类需要先申明一个父类的对象然后才能调用子类。

于是做了以下实验

public class test {    public static class abc {    }       public static void main(String[] args) {        abc var = new abc();    }   }


这样代码就可以编译通过.



上一篇:一个使用Java语言描述的矩阵旋转的例子
下一篇:《C 程序设计语言》 第八章 malloc 函数实现于内测管理

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年03月25日 16时50分52秒