Pawan Mall
Pawan Mall

Reputation: 91

Need to create a custom class in JAVA

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...


  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

Upvotes: 3

Views: 15857

Answers (3)

Angelo Fuchs
Angelo Fuchs

Reputation: 9941

Your student class is nested inside the main class. As you haven't declared it as static, it is therefore an inner class. The Java Tutorial says that:

An instance of InnerClass can exist only within an instance of 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.

class main {

    static class student {
        public int rollno;

Upvotes: 2

Nishant
Nishant

Reputation: 32233

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

main m = new main();

student s= m.new student(); 

Upvotes: 1

Vu.N
Vu.N

Reputation: 149

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"

Upvotes: -1

Related Questions