Ans :As the Inheritance Grows it is not good to keep up the Long Chains in Inheritance.
What is Delegation?
Ans: Meaning from Dictionary : "To work with a set or specified goal or purpose."
The Meaning Itself spells what is Delegation, the Same can be Applied here in Java.
Delegation is simply passing a duty off to someone/something else.
In True the Delegation is Something can be Described like this
1) The object that forwards the request also passes itself as an argument to the delegate object,which actually does the work.
2) Delegation can be viewed as a relationship between the Objects where one object
forwards certain method calls to another object,called its delegate.
forwards certain method calls to another object,called its delegate.
Advantages of Delegation:
1) Delegation is run-time flexibility: The delegates can easily be changed at run-time.
Comparison between Inheritance and Delegation:
1) unlike Inheritance it does not force you to accept all the methods of a super class.
2)Use an object of known class,and forward a message to that Instance rather than
a new class in Inheritance.
a new class in Inheritance.
3) Inheritance is restricted to Compile time.
Here is a simple example:
Code:
public class Information
{
public String getTemperature()
{
return TempGetter.getTemperature();
}
public String getTime()
{
return TimeGetter.getTime();
}
}
In this example, I've got imaginary classes "TimeGetter" and "TempGetter" that have
Code:
public class Information
{
public String getTemperature()
{
return TempGetter.getTemperature();
}
public String getTime()
{
return TimeGetter.getTime();
}
}
In this example, I've got imaginary classes "TimeGetter" and "TempGetter" that have
static methods for retrieving time and temperature. Rather than finding my own way to obtain these data, I use existing classes. Said another way, I delegate these tasks to
these classes without knowing/caring about the details of how it gets done.
NOTE :
Delegation can be termed "run-time inheritance for specific objects".
Example:
For instance, when the user clicks the close box, the delegate is sent a windowShould
Close: call, and the delegate can delay the closing of the window if there is unsaved data represented by the window's contents.
Close: call, and the delegate can delay the closing of the window if there is unsaved data represented by the window's contents.
No comments:
Post a Comment