0

Hello I have an assignement which is to create an iterative add method add(Student s) in the adequate class without getters and setters but I may create " auxilliary method" (not sure what it means) and attributs.

I've tried to make the method add in Group class :

public void add(Student s) {
    if ( head == null) {
        head = new Student(...); 
        // Struggling because Student constructor requires a String not a Student

    }
}

I could've done it by creating a getter for the name, like this head = new Student(s.getName()); but I'm not allowed to use getters and setters, what can I do ? thank you

public class Student {

    private final String name;
    private int grade;
    private Student next;

    private static int counter = 0;

    public Student(String name) {
        this.name = name;
        this.grade = 0;
    }

}

public class Group {

    private int groupnumber;
    private Student head;

    // Empty list & group number by default is 2
    public Groupe() {
        this.head = null;
        this.groupnumber = 2;
    }
}

1 Answer 1

1

You can use a copy constructor. Like new Student(student).

public class Student {

    private final String name;
    private int grade;
    private Student next;

    private static int counter = 0;

    public Student(Student template) {
        this.name = template.name;
        this.grade = template.grade;
    }

}

Or, maybe more simple:

public void add(Student s) {
    if ( head == null) {
        head = s; 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.