首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >学生a=new错误学生();

学生a=new错误学生();
EN

Stack Overflow用户
提问于 2016-11-14 09:36:53
回答 5查看 1.4K关注 0票数 1

我收到的错误如下:

线程"main“java.lang.Error中的异常:未解决的编译问题: 无法访问New类型的封闭实例。必须将分配限定为包含New类型的实例(例如,x.new A(),其中x是New的实例)。在n.New.main(New.java:7)

以下是我的代码:

代码语言:javascript
复制
package n;

public class New 
{

    public static void main(String[] args) 
    {
        Student a=new Student();
        a.name="abc";
        a.number=6;
        a.marks=1;

        System.out.println(a.name);
        System.out.println(a.number);
        System.out.println(a.marks);
    }

    class Student
    {
        String name;
        int number;
        int marks;

    }

}
EN

回答 5

Stack Overflow用户

发布于 2016-11-14 09:42:37

您的类学生不是静态的,您正在尝试从不允许的静态上下文中访问它。

您的代码应该如下:

代码语言:javascript
复制
package n;

public class New {

    public static void main(String[] args) {
        Student a = new Student();
        a.name = "abc";
        a.number = 6;
        a.marks = 1;

        System.out.println(a.name);
        System.out.println(a.number);
        System.out.println(a.marks);
    }

    static class Student {
        String name;
        int number;
        int marks;

    }

}
票数 2
EN

Stack Overflow用户

发布于 2016-11-14 09:43:53

Student是类New的非静态内部类,必须从类New的对象中访问。它不能直接从main访问,因为main是静态的,Student不是静态的。作为一种解决方案,只需在New之外声明如下:

代码语言:javascript
复制
package n;

public class New {

    public static void main(String[] args) {
        Student a = new Student();
        a.name = "abc";
        a.number = 6;
        a.marks = 1;

        System.out.println(a.name);
        System.out.println(a.number);
        System.out.println(a.marks);
    }
}

class Student {
    String name;
    int number;
    int marks;

}
票数 1
EN

Stack Overflow用户

发布于 2016-11-14 09:44:57

之所以会发生编译错误,是因为StudentNew的内部类。

由于Student被定义为class Student,它只能存在于New实例中。因此,有几种方法可以解决这个“问题”。

最简单的一个:做好

代码语言:javascript
复制
static class Student 

因此,Student的单个实例不一定存在于New实例中。

另一个是创建一个New实例,在其中创建一个Student实例:

代码语言:javascript
复制
Student a = new New().new Student();

但是,为了开始学习如何编程,我要说:删除内部Student类,并以Student作为外部类开始。

代码语言:javascript
复制
public class Student {
    String name;
    int number;
    int marks;

    public static void main(String[] args) {
        Student a = new Student();
        a.name = "abc";
        a.number = 6;
        a.marks = 1;

        System.out.println(a.name);
        System.out.println(a.number);
        System.out.println(a.marks);
    }
}

启动程序增加了以下几个部分:

Student中包含一个构造函数作为Student(String, int, int),并在初始化Student的新实例时调用它,而不是初始化它并在之后设置变量:

代码语言:javascript
复制
new Student("abc", 1, 6); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40585598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档