How can you make sure
that two instances are equal
- Both the instances belong to the same class
- The values of the member variables are equal
The two different ways by
which we can relate classes is by
1. Inheritance
2. Composition.
Composition is attained
by defining instance variables that are references to other objects.
Class Fruit {
}
Class Apple {
Private Fruit fruit = new Fruit();
}In a composition the Apple class is called 'Front End' class and Fruit class is called 'Back end' class. Here the front end class will hold a reference in its instance variable to a back end class. The composition got a "HAS - A " relationship between the front end and back end classes, where as inheritance is "IS-A" relationship.
Advantages of Inheritance
1. Code re-use
2. Dynamic Binding - The JVM will decide at run time which method implementation needs to be called based on the class of the object.
3. Polymorphism
One of the prime benefits of dynamic binding and polymorphism is that they can help make code easier to change.
If you have a fragment of code that uses a variable of a superclass type, such as
Fruit
, you could later create a brand new subclass, such as Banana
, and the old code fragment will work without change with instances of the new subclass. If Banana
overrides any of Fruit
's methods that are invoked by the code fragment, dynamic binding will ensure that Banana
's implementation of those methods gets executed. This will be true even though class Banana
didn't exist when the code fragment was written and compiled.
No comments:
Post a Comment