0

I am new at Java and lately I study class and object topics. However, I could not progress of this code:

public class ClassStudy {

// Student Group
class Student {

    public String name = null;
    public String surname = null;

    boolean study(boolean does) {
        // He studies.
        boolean d = does;
        return d;
    }
    boolean slackOff(boolean does) {
        // He slacks off.
        boolean d = does;
        return d;
    }
}

// Teacher Group
class Teacher {

    public String name = null;
    public String surname = null;

    boolean teach(boolean does) {
        // He teaches.
        boolean d = does;
        return d;
    }
    boolean learn(boolean does) {
        // He learns.
        boolean d = does;
        return d;
    }
}

// Main Method
public static void main(String[] args) {
    Student student = new Student();
    Teacher teacher = new Teacher();
}

}

In main method, I got errors of student, yet did not got of teacher. I do not know if I have done any mistake or I can not see it. What has to be done?

The errors I get:

  • The value of the local variable student is not used
    • No enclosing instance of type ClassStudy is accessible. Must qualify the allocation with an enclosing instance of type ClassStudy (e.g. x.new A() where x is an instance of ClassStudy).
    • Line breakpoint:ClassStudy [line: 44] - main(String[])
Eray Erdin
  • 2,633
  • 1
  • 32
  • 66

3 Answers3

4

Either make the Student (and Teacher) class static or make it a top level class

static class Student {
   ...
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 3
    Those should really be top level classes unless you have a really good reason to make them public static inner classes. -- EDIT -- Just saw that they are not public so I'll reserve my judgement lol. O.O – jgitter Apr 24 '14 at 14:27
3

The error already states the problem:

No enclosing instance of type ClassStudy is accessible. Must qualify the allocation with an enclosing instance of type ClassStudy (e.g. x.new A() where x is an instance of ClassStudy).

You cannot create instances of inner classes without having an instance of their surrounding class, except when they're static. So what you need to change your main method to:

// Main Method
public static void main(String[] args) {
    ClassStudy classStudy = new ClassStudy();
    Student student = classStudy.new Student();
    Teacher teacher = classStudy.new Teacher();
}

The reason you're not getting that same error on the line where you initialize Teacher, is because the compiler stops compiling at the first error it finds.

Smokez
  • 382
  • 1
  • 5
1

Reimeus has a correct solution. To understand what the message was telling you, you should read up on what static and non-static inner classes are. These should get you started.

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Java inner class and static nested class

Community
  • 1
  • 1
jgitter
  • 3,396
  • 1
  • 19
  • 26