java 需要在JAVA中创建自定义类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10136209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:44:46  来源:igfitidea点击:

Need to create a custom class in JAVA

javaclass

提问by Pawan Mall

I want to create a custom class object in JAVA and i created but it is showing an error...doesn't know why this error occurring, please help me coz i'm starting to learn JAVA earlier...

我想在 JAVA 中创建一个自定义类对象,我创建了但它显示一个错误......不知道为什么会发生这个错误,请帮助我因为我更早开始学习 JAVA......


  class main {

    class student {
        public int rollno;
        public String name;
        public int marks;

        public void accept() {
            rollno = 1;
            name = "Pawan Mall";
            marks = 100;
        }

        public void display() {
            System.out.println(rollno);
            System.out.println(name);
            System.out.println(marks);
        }

    }

    public static void main(String argv[]) {
        student s = new student();
        s.accept();
        s.display();
    }

}

It was occurring at the time of compile that is the error which i faced while i compile the code :

它发生在编译时,这是我在编译代码时遇到的错误:

C:\Program Files\Java\jdk1.7.0_03\bin\student.java:28: error: non-static variable this cannot be referenced from a static context
student s = new student();
            ^
1 error

Tool completed with exit code 1

采纳答案by Angelo Fuchs

Your studentclass is nestedinside the mainclass. As you haven't declared it as static, it is therefore an innerclass. The Java Tutorialsays that:

您的student嵌套main类中。由于您尚未将其声明为static,因此它是一个inner类。Java 教程说:

An instance of InnerClass can exist only within an instance of OuterClass.

InnerClass 的实例只能存在于 OuterClass 的实例中。

Since that is exactly what you are trying to do, it fails.

因为这正是你想要做的,所以它失败了。

Your studentclass needs to be static, so you can instantiate it in a static context.

你的student类需要是静态的,所以你可以在静态上下文中实例化它。

class main {

    static class student {
        public int rollno;

回答by Nishant

Try creating the instance of student using main class reference like this

尝试使用这样的主类引用创建学生实例

main m = new main();

student s= m.new student(); 

回答by Vu.N

The first char of name class must be capital. The name of class and name of file are the same. In you case: "student" -> "Student"

name 类的第一个字符必须是大写。类名和文件名相同。在你的情况下:“学生”->“学生”