Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decide whether use IS A or HAS A Relation

Tags:

oop

public class B {

    public String getMe()
    {
        return "Some";
    }
}

Assume that i have a above class , by which parameters should we decide what to use ?? Whether is a or Has a Relation ??

HAS - A

public class A {



    public static void main(String args[])
    {
        B b = new B();
        System.out.println(b.getMe());
    }
}

or

public class A  extends B
{


    public static void main(String args[])
    {
        A b = new A();
        System.out.println(b.getMe());
    }
}
like image 722
Pawan Avatar asked Jun 18 '11 10:06

Pawan


People also ask

When to Use is a and has a relationship?

An IS-A relationship is inheritance. The classes which inherit are known as sub classes or child classes. On the other hand, HAS-A relationship is composition.

When to Use is a and has a relation in Java?

Wherever you see an extends keyword or implements keyword in a class declaration, then this class is said to have IS-A relationship. HAS-A Relationship: Composition(HAS-A) simply mean the use of instance variables that are references to other objects. For example Maruti has Engine, or House has Bathroom.

What is has a and IS-A relationship with example?

Has-a is a special form of Association where: It represents the Has-A relationship. It is a unidirectional association i.e. a one-way relationship. For example, here above as shown pulsar motorcycle has an engine but vice-versa is not possible and thus unidirectional in nature.

Is a and has a relationship in C#?

Note: In C#, the IS-A relationship is implemented using Inheritance and the HAS-A relationship is implemented using Composition i.e. declaring a variable. So, whenever we declare a variable of one class inside another class, we called it a Composition or you can say HAS-A relationship.


1 Answers

Depends on the logical relation. It just needs to make sense.

Example:

Lets say you have Animal classes.
So you have these classes: Animal, Dog, Cat , Leopard, Fur, Feet

Cat and Dog IS A Animal.
Leopard IS A Cat.
Animal HAS A Fur, Feet.

In a nutshell:

IS A relationship means you inherit and extend the functionality of the base class.
HAS A relationship means the class is using another class, so it has it as a member.

like image 73
Yochai Timmer Avatar answered Oct 10 '22 04:10

Yochai Timmer