Discuss / Java / 出现问题问题

出现问题问题

Topic source

Habin

#1 Created at ... [Delete] [Delete and Lock User]
public class Class {
    public static void main(String[] args) {
        City bj = new City();
        bj.name = "Beijing";
        bj.latitude = 39.903;
        bj.longitude = 116.401;
        System.out.println(bj.name);
        System.out.println("location: " + bj.latitude + ", " + bj.longitude);
    }
    class City{
        public String name;
        public double latitude;
        public double longitude;
    }
}

JDK 17 LTS

无法从 static 上下文引用 'Class.this' 

需要将City类设置为static才可以,有大佬讲讲原因么?

Habin

#2 Created at ... [Delete] [Delete and Lock User]
E:\Study\javacode\chapter06>javac Class.java
Class.java:3: 错误: 无法从静态上下文中引用非静态 变量 this
        City bj = new City();
                  ^
1 个错误

报错

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

往后看内部类


  • 1

Reply