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
Need to create a custom class in JAVA
提问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 student
class is nestedinside the main
class. As you haven't declared it as static
, it is therefore an inner
class. 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 student
class 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 类的第一个字符必须是大写。类名和文件名相同。在你的情况下:“学生”->“学生”