Relationships in JAVA
In general relationship is two or more people/things are connected. In java relationship is how
classes /objects are connected.
There are two types of relationships in JAVA
i] Is a relationship [ Inheritance ]
ii] Has a relationship[ Aggregation/composition]
Is a relationship:
If the class is a subclass of another class, this denotes "is a" relationship.
"IS A" relationship refers to Inheritance.This relationship is achieved in JAVA by the keyword
"extends".
For example, we have animal class and dog class. In this case, dog is a animal.
class animal{
}
class dog extends animal{
}
Dog is a subclass and animalclass is the superclass.
click here to know about Inheritance in JAVA.
Has a relationship:
We know an object is an instance of a class. Consider a student who has address.
In this case,we will have student class and address class.address class will have streetno,
streetname, city and state.
class Student{
int studentID;
String studentName;
Address address; //Addresss is a class
}
Class Address{
int streetNumber;
String streetName;
String city;
String state;
}
Here student has a address[ Aggregation]. Here Student exists without address and
address exists without student. This kind of loose coupling is called Aggregation.If there is tight coupling exists between two classes involved, then it is Composition.
Aggregation and composition denotes "has a relationship".
In general relationship is two or more people/things are connected. In java relationship is how
classes /objects are connected.
There are two types of relationships in JAVA
i] Is a relationship [ Inheritance ]
ii] Has a relationship[ Aggregation/composition]
Is a relationship:
If the class is a subclass of another class, this denotes "is a" relationship.
"IS A" relationship refers to Inheritance.This relationship is achieved in JAVA by the keyword
"extends".
For example, we have animal class and dog class. In this case, dog is a animal.
class animal{
}
class dog extends animal{
}
Dog is a subclass and animalclass is the superclass.
click here to know about Inheritance in JAVA.
Has a relationship:
We know an object is an instance of a class. Consider a student who has address.
In this case,we will have student class and address class.address class will have streetno,
streetname, city and state.
class Student{
int studentID;
String studentName;
Address address; //Addresss is a class
}
Class Address{
int streetNumber;
String streetName;
String city;
String state;
}
Here student has a address[ Aggregation]. Here Student exists without address and
address exists without student. This kind of loose coupling is called Aggregation.If there is tight coupling exists between two classes involved, then it is Composition.
Aggregation and composition denotes "has a relationship".
Sign up here with your email
ConversionConversion EmoticonEmoticon