Reputation: 174
My application model consists of disorders, each of which has innate attributes (id, name, incidence, etc.) and relationships to other disorders (e.g. risk factors, precipitating disorders, findings). I've considered the following two object models:
The first: nested classes:
class DiagnosticElement{
Disorder disorder;
List<Disorder> relatedDisorders;
static class Disorder {
int id;
String name;
double incidence;
Disorder(id){
this.id=id;
}
}
}
The second:
class Disorder {
int id;
String name;
double incidence;
List<Disorder> relatedDisorders;
Disorder(id){
this.id=id;
this.relatedDisorders=new ArrayList<Disorder>()
}
}
The second approach seems simpler. Of course I must first instantiate Disorder objects before I can reference them in the ArrayList. Is one approach better than the other?
Upvotes: 3
Views: 81
Reputation: 6717
Careful, your line
List<Disorder> relatedDisorders=new ArrayList<Disorder>()
in the constructor will create a local variable relatedDisorders
, which you initialize. You did not initialize the class field.
Anyway, there is nothing wrong with having references to your own class inside your class. That is how every linked list works.
Upvotes: 0
Reputation: 285403
There's nothing wrong with approach number two, and in fact it is used quite often. Think of Trees or LinkedLists for instance where nodes hold links to other nodes. You do have to be careful if you create objects of the same type inside of a constructor though as this can lead to code that runs forever.
Upvotes: 7