“非静态变量 this 不能从静态上下文中引用"创建对象时 [英] "Non-static variable this cannot be referenced from a static context" when creating an object

查看:46
本文介绍了“非静态变量 this 不能从静态上下文中引用"创建对象时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来测试 Java 中类和对象的概念.

I wrote the below code to test the concept of classes and objects in Java.

public class ShowBike {
    private class Bicycle {
        public int gear = 0;
        public Bicycle(int v) {
            gear = v;
        }
    }

    public static void main() {
        Bicycle bike = new Bicycle(5);
        System.out.println(bike.gear);
    }
}

为什么在编译过程中会出现以下错误?

Why does this give me the below error in the compiling process?

ShowBike.java:12: non-static variable this cannot be referenced from a static context
        Bicycle bike = new Bicycle(5);
                       ^

推荐答案

使 ShowBike.Bicycle 成为静态.

public class ShowBike {

    private static class Bicycle {
        public int gear = 0;
        public Bicycle(int v) {
            gear = v;
        }

    }

    public static void main() {
        Bicycle bike = new Bicycle(5);
        System.out.println(bike.gear);
    }
}

在 Java 中有两种类型的嵌套类:静态嵌套类"和内部类".如果没有 static 关键字,它是一个内部类,您将需要一个 ShowBike 的实例来访问 ShowBike.Bicycle:

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

ShowBike showBike = new ShowBike();
Bicycle bike = showBike.new Bicycle(5);

<小时>

静态嵌套类和普通(非嵌套)类在功能上几乎相同,只是对事物进行分组的方式不同.但是,在使用静态嵌套类时,不能将它们的定义放在单独的文件中,这会导致单个文件包含很多类定义.


Static nested classes and normal (non-nested) classes are almost the same in functionality, it's just different ways to group things. However, when using static nested classes, you cannot put definitions of them in separated files, which will lead to a single file containing a lot of class definitions.

这篇关于“非静态变量 this 不能从静态上下文中引用"创建对象时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆