0
public class Student {
    int rollNumber;
    String name;
    int noOfSubjects;
    ArrayList<Subject> subjectList = new ArrayList<>();

    public TestStudent(int rollNumber, String name, int noOfSubjects) {
        super();
        this.rollNumber = rollNumber;
        this.name = name;
        this.noOfSubjects = noOfSubjects;

    }

    // inner class
    public class Subject {
        String subjectName;
        int marks;

        public Subject(String subjectname, int marks) {
            super();
            subjectName = subjectname;
            this.marks = marks;
        }

        public int getSubjectMarks() {
            return marks;

        }

    }

    public void addSubject(Subject s) {
        subjectList.add(s);

    }

    public int getMarks(Subject s) {
        return s.getSubjectMarks();
    }

like in above class Student ,there is an inner class Subject which contains inforamtion of subject names and corresponding marks student has got so if i want to print all subject names and respective marks along with the student details , how can we do it ?

greg-449
  • 109,219
  • 232
  • 102
  • 145
Alok Mishra
  • 926
  • 13
  • 39
  • 1
    Just as you would do with a top-level class: by looping over the subjects in subjectList. Note that this Subject class has no reason to be an inner class. It could be a static nested class, but even then, why? – JB Nizet Jan 16 '15 at 11:50
  • yes it could be a static nested class but this was an assignment to me and i have to do it in that way only .(Note : i am not cheating on my teacher as i have already submitted the assignment thought i am cusious to know how we access inner class's non static members from outer class .)@JBNizet – Alok Mishra Jan 16 '15 at 11:59
  • As I said: exactly the same way as you would with any other class: `for (Subject s : subjectList) { System.out.println(s.getSubjectMarks()); }` – JB Nizet Jan 16 '15 at 12:02
  • This way you can access the inner class members from outer class [more info](http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html) `Student stud = new Student(); Student.Subject subject = stud.new Subject("somestring", 1);` – FrAn Jan 16 '15 at 12:32

0 Answers0