2

We use extends keyword for using is-a relationship in Java using OOP. But on the other side, we also have has-a relationship and we use reference of the first class in 2nd class for has-a relationship. My question is, if we have a has-a relationship, can we use extends keyword in implementation?

Suppose we have the example here:

A “university” has several “departments”. Without the existence of “university”, there is no chance for the “departments” to exist.

Can we write it as (just a rough example for understanding)

class University extends Department
{
   Department d = new Department();
   University(String name, Department d)
    {
        this.Name=name;
        this.Department = d;    
    }    
}

or when we make an entity of one class in another we can not use word extends?

Dee_wab
  • 1,171
  • 1
  • 10
  • 23
AHF
  • 1,070
  • 2
  • 15
  • 47
  • Possible duplicate of [Prefer composition over inheritance?](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – Bogdan Lukiyanchuk Apr 14 '18 at 12:41
  • I guess you can but that’s what implements is for. – Sean Apr 14 '18 at 12:44
  • Your design compiles, so it is possible. But why do you need to extend from `Department`. The class also works without it. – CoronA Apr 14 '18 at 12:45
  • I was just thinking that this 'extends' keyword in Java is only for 'is-a relationship' or for any kind of inheritance including has a relationship – AHF Apr 14 '18 at 12:47

2 Answers2

1

You cant do it with extends, but you could use an interface, as follows:

interface HasDepartments {
    public Set<Departments> getDepartments();
}

class University implements HasDepartments {
    private final String name;
    private final Set<Department> departments = new HashSet<Department>();
    University(String name, Collection<Department departments) {
        this.name=name;
        this.departments = departments;    
    }
    public Set<Departments> getDepartments() {
        return departments;
    }
 }

However, unless there were other things that could have departments, I wouldn't bother. Just University having a getDepartments() method is enough.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Thanks for your answer, again in my question, Can we use 'extends' keyword when we have 'has-a relationship'. – AHF Apr 14 '18 at 12:46
  • 1
    @AHF as per the first sentence in my answer *you can't do it with `extends`*... no. – Bohemian Apr 14 '18 at 12:48
0

I suggest you to see this link, to understand difference between is-a and has-a relationship What is the difference between IS -A relationship and HAS-A relationship? Java

also search for composition, aggregation, association in java (has-a relationship types)

to answer your question, There is no obstacle to use it but you need a good reason to inherit University from Department.

Arya
  • 91
  • 4