Java – use objects in your own constructors
Is it possible (or wise) to use an object in its own constructor? (sorry for the noob problem of improper production)
Suppose I have a "student" class, which contains the ArrayList of the subclass student and a method to add a new student to the array
Can I use the addstudent method in my student constructor to add a new instance to the array at creation time like this:
//Students class Students{ private static ArrayList<Student> STUDENTS = new ArrayList<>(); public static void addStudents(Student student){ STUDENTS.add(student); } } //Student class Student /*extends Students <- old misstake left for reference*/{ private String name = ""; private int birthYear = 0; Student(String _name,int _birthYear){ this.name = _name; this.birthYear = _birthYear; //insert wild guess Students.addStudents(this(name,birthYear)); } }
Or will it simply loop and create many objects until everything crashes?
Solution
You can; You shouldn't
One reason is that you may not always want to add all student instances to the same shared list For example, if you create student instances in a unit test and add them to the students list of the constructor, you must worry about clearing the list after the test to avoid accidental sharing of state between tests
Another reason is to add an instance in the constructor called unsafe publication You are providing a reference to an instance that has not been fully initialized This can lead to some very tricky errors, especially those related to concurrency
Before doing anything, you should always wait for the instance to initialize completely (that is, a new whatever returns)
You'd better decouple creating a student from adding to the student list Create a student using the factory method:
class Students{ private static ArrayList<Student> STUDENTS = new ArrayList<>(); public static void addStudents(Student student){ STUDENTS.add(student); } // Factory method. public static Student createAndAddStudent(String name,int birthYear) { Student student = new Student(name,birthYear); addStudents(student); return student; } }
As far as your current code is concerned, you do not need to extend students Logically, students are not students, not just cars, not cars (say it out loud; it just doesn't make sense)
All you need to do is call the static method:
class Student { Student() { // ... Students.addStudents(this); // ... } }