A
business has many objects. All these objects must be related to each other.
Java supports three types of relations between objects –
1. IS-A (Inheritance) – We should
establish IS-A relation between classes for grouping classes as one category or
family to establish child-parent relation so, that child classes objects can be
used wherever parent class referenced variable is used.
In the above example : Student
and Employee objects are grouped as one family of classes and they got the type
Person. Then these two objects inherit the properties and behaviors of Person. Now
these objects are also of type Person, this is the reason we call them as
- · Student IS-A Person
- · Employee IS-A Person
We can implement this IS-A
relation using the following two keywords –
- · extends – It is used between two classes or two interfaces.
- · implements – It is used between a class and interface.
2. HAS-A (Composition) – We should establish HAS-A relation between classes, if one object
cannot exist without another object. For example, in the above example a
student or employee object cannot exist without address. Hence, we must
establish HAS-A relation between these objects. This is the reason we call them
as –
- · Student HAS-A Address
- · Employee HAS-A Address
This relation is implemented by
storing other object’s instance, using its non-static variable in our object’s
classes. Hence, we must create Address class type non-static variable to store
its object in Student and Employee classes.
Example –
class Address{
}
class Student
{
Address add = new Address();
}
Class Employee
{
Address add = new Address();
}
3. USES-A (Aggregation) – We should establish USES-A relation between classes if one object
uses another object for performing one of its operations. Example – An application
to create Student and Bike objects for developing USES-A relation between these
two objects.
class
Bike{
String bikenumber;
String bikename;
int modelnumber;
String enginenumber;
}
class
Student{
int sno;
String sname;
String course;
void
goingToCollegeBy(Bike b)
{
System.out.println(this.sname+" : is going to college by : "+b.bikename+"
bike");
}
}
public class
Test {
public static void
main(String[] args) {
Bike ktm
= new Bike();
ktm.bikename="KTM-220";
ktm.bikenumber="3122";
ktm.enginenumber="44321as";
ktm.modelnumber=2016;
Student s = new
Student();
s.sno=26;
s.sname="Rakesh";
s.course="MCA";
s.goingToCollegeBy(ktm);
}
}
Output –
Rakesh : is going to college by
: KTM-220 bike
No comments:
Post a Comment