Provide Best Programming Tutorials

Relationship in Java

Relationship in Java

Type of relationship always makes to understand how to reuse the feature from one class to another class. In java programming we have three types of relationship they are.

  • Is-A Relationship
  • Has-A Relationship
  • Uses-A Relationship

Is-A relationship

In Is-A relationship one class is obtaining the features of another class by using inheritance concept with extends keywords.

In a IS-A relationship there exists logical memory space.

 Is-A relation

Example of Is-A Relation

Example

package com.andrewProgramming;

class Faculty {

  float salary = 30000;
}

class Science extends Faculty {

  float bonous = 2000;

  public static void main(String args[]) {
    Science obj = new Science();
    System.out.println("Salary is:" + obj.salary);
    System.out.println("Bonous is:" + obj.bonous);
  }
} 

Output

Salary is: 30000.0  
Bonous is: 2000.0

Has-A relationship

In Has-A relationship an object of one class is created as data member in another class the relationship between these two classes is Has-A.

In Has-A relationship there existed physical memory space and it is also known as part of or kind of relationship.

 Has-A relation

Example of Has-A Relation

Example

package com.andrewProgramming;

class Employee {

  float salary = 30000;
}

class Developer extends Employee {

  float bonous = 2000;

  public static void main(String args[]) {
    Employee obj = new Employee();
    System.out.println("Salary is:" + obj.salary);
  }
}  

Output

Salary is: 30000.0  

Uses-A relationship

A method of one class is using an object of another class the relationship between these two classes is known as Uses-A relationship.

 Uses-A relation

As long as the method is execution the object space (o1) exists and once the method execution is completed automatically object memory space will be destroyed.

Example of Uses-A Relation

Example

package com.andrewProgramming;

class Employee {

  float salary = 30000;
}

class Salary extends Employee {

  void disp() {
    float bonous = 1000;
    Employee obj = new Employee();
    float Total = obj.salary + bonous;
    System.out.println("Total Salary is:" + Total);
  }
}

class Developer {

  public static void main(String args[]) {
    Salary s = new Salary();
    s.disp();
  }
} 

Output

Total Salary is: 31000.0

Note 1: The default relationship in java is Is-A because for each and every class in java there exist an implicit predefined super class is java.lang.Object.

Note 2: The universal example for Has-A relationship is System.out (in System.out statement, out is an object of printStream class created as static data member in another system class and printStream class is known as Has-A relationship).

Note 3: Every execution logic method (main() ) of execution logic is making use of an object of business logic class and business logic class is known as Uses-A relationship.

Leave a Reply

Close Menu