OOPs concepts – What is Association in java?
Association establishes relationship between two separate classes through their objects. The relationship can be one to one, One to many, many to one and many to many.
Association Example:
class CarClass{
String carName;
int carId;
CarClass(String name, int id)
{
this.carName = name;
this.carId = id;
}
}
class Driver extends CarClass{
String driverName;
Driver(String name, String cname, int cid){
super(cname, cid);
this.driverName=name;
}
}
class tc{
public static void main(String args[])
{
Driver obj = new Driver("Santhoshi", "rolls royce", 9988);
System.out.println(obj.driverName+" is a owner of"+" "+obj.carName+" "+"carId: "+obj.carId);
}
}
Output:
C:\Users\PRIYA\Desktop\java>javac tc.java
C:\Users\PRIYA\Desktop\java>java tc
Santhoshi is a driver of rolls royce carId: 9988
In the above example, there is a one to one relationship(Association) between two classes: CarClass and Driver. Both the classes represent two separate entities.
Comments
Post a Comment