dido
dido

Reputation: 3407

Java has-a relationship

Would the below be correct for the following statement. "A man has a best friend who is a dog."

public class Mann {
     private BestFriend dog;
     //etc
}

Upvotes: 2

Views: 7334

Answers (4)

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28713

Looks like Dog should by type, because man can have other "type of best friend":

public class Mann {
     private Dog bestFriend;
     //etc
}

Update

Most close to real-live implementation will look like:

public interface Friend {}

public class Man implements Friend {}

public class Dog implements Friend {}

public class FriendRelationship {
    private Friend first;
    private Friend second;

    public FriendRelationship(Friend first, Friend second) {
        this.first = first;
        this.second = second;
    }
}

Man aPerson = new Man();
Dog aBog = new Dog();
FriendRelationship bestFriends = new FriendRelationship(aPerson, aDog);

This way one can express friend relationships between any entities. Common base class is not required. You only need implement Friend interface.

Upvotes: 2

jli
jli

Reputation: 6623

I'd say it would be more correct to write:

public class Man extends Entity {
     private Entity bestFriend = new Dog(); // Where Dog extends Entity
     //etc
}

Why? Let's say you have a bunch of different entities, say Man, Cat, and Dog. It would then make sense to have them each extend an Entity class, that specifies various attributes every entity should have. Each one, then, could have a bestFriend attribute, that could be any other Entity.

However, as pointed out in the comments, it would be even more correct to allow for specifying a bestFriend in the constructor:

public class Man extends Entity {
    private Entity bestFriend;

    public Main(Entity bestFriend) {
        this.bestFriend = bestFriend;
    }
    //etc
}

...

Dog bobDog = new Dog();
Man bob = new Man(bobDog);

Upvotes: 5

Volvox
Volvox

Reputation: 621

One extra 'n' in man, otherwise it seems reasonable.

Upvotes: 1

Hawken
Hawken

Reputation: 2119

public class Man extends world.life.animalia.chordata.mammalia.primates.hominidae.hominini.homo.Homo_sapiens {
    private world.life.animalia.chordata.mammalia.carnivora.canidae.canis.c_lupus.CanisLupusFamiliaris dog = new world.life.animalia.chordata.mammalia.carnivora.canidae.canis.c_lupus.CanisLupusFamiliaris();
    private concept.population.social.Friend bestFriend = dog;
}

this way bestFriend is a pointer (or reference) to the dog.

Upvotes: 1

Related Questions