Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - When should I use generics to define relationships between types?

Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.

Say I have:

public class Honda implements ICar(){
}

public class Opel implements ICar(){
}

Should I use:

public class Person{
    ICar car;
    .
    .
    public Person (ICar c){
        car = c;
    }
}

or

public class Person<T extends ICar>{
    T car;
    .
    .
    public Person(T c){
        car = c;
    }
}

or does it depend on the tasks performed?

Are generics only for aggregation relationships (containers etc); that is, are they just used for collections?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.

Think about what you try to mimic from the real world, before going into such programming details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...