How can a child interface reuse its parents' implementations? - java

Recently I had an interview and I was asked the following question. Given the following class/interface structure:
Question:
How can one implement interface EmployedStudent to reuse code from StudentImpl and EmployeeImpl.
I suggested to compose Employee and Student into my implementation.
Based on the interviewer's reaction I don't think they found it to be the best solution. I spent a lot of time thinking about it but I cannot come up with another solution.

Create a class that implements both Employee and Student. In your class, create an instance of both EmployeeImpl and StudentImpl. Make your class delegate all method calls to either one of the objects then.
public class EmployedStudent implements Employee, Student {
private EmployeeImpl employee = new EmployeeImpl();
private StudentImpl student = new StudentImpl();
public int getSalary() {
return this.employee.getSalary();
}
public float getAverageGrade() {
return this.student.getAverageGrade();
}
}

So, you could have implements Employee, Student internally delegating to both EmployeeImpl and StudentImpl, but also inherit from one implementation class.
Now the class name EmployedStudent (not StudyingEmployee or BothEmployeeAndStudent) suggests:
class EmployedStudent extends StudentImpl implements Employee {
Employee asEmployee = new EmployeeImpl();
Yeah, a tiny bit more efficient as only delegating to one other class.
The use-case is however far from realistic: all kind of combinations are thinkable of several classes. In that case your solution is more universal. Really universal, is a lookup-mechanism:
public class Person {
public <T> T as(Class<T> klazz) { ... }
}
Person person = ...;
Student asStudent = person.as(Student.class);
if (asStudent != null) {
...
}
Employee asEmployee = person.as(Employee.class);
if (asEmployee != null) {
asEmployee.quitJob();
asEmployee = person.as(Employee.class); // null
}
That is a lookup of capabilities. It typically can replace a cumbersome inheritance hierarchy, say of Vehicle, RoadVehicle, SwimmingVehicle (boat), FlyingVehicle (air plane), WaterAirplane (?), AmphibianTank (?) by using capabilities Swimming, Flying, Driving.
The difference is the entire decoupling.

As java doesn't support multiple inheritance, you could/should
either have a field for each of the wanted superclasses
or derive from one superclass and have a field for the other one.
The fields are then referred to by "our" implementation of the respective methods.
This is one of the design patterns from the GoF, I think it is the Proxy pattern.

With Java 8, you can move code into the interface itself. That solves the "multiple inheritance" problem.

While the Interface Segregation Principle can sometimes be helpful, and some people scoff at the idea of interfaces which don't promise that all implementations will support all members, I would suggest that it may be helpful to have Student and Employee interfaces which include isStudent and isEmployee members, and then have Person implement both interfaces; some methods like giveRaise() shouldn't work on someone who isn't an employee, but others like getOutstandingPay() should work just fine (if someone hasn't earned any money, the method should simply return zero).
While it may seem ugly to complicate all Person objects with methods that won't be applicable for many of them, such a design avoids difficulties in the event that a student gets hired, or an employee starts taking classes. Having separate classes for Student, Employee, and StudentEmployee, even if one could do so easily, would require that a Student who got a job be replaced with a new object instance in order to become a StudentEmployee. By contrast, if one has a Person class whose instances may or may not be able to handle methods like giveRaise, then one can handle situations where objects' abilities change during their lifetimes.

Related

Generic Method with different argument but same return type

I have multiple methods which accept different types in arguments but have the same return type. I am planning to create a generic method but not sure of the implementation.
Method 1 :
private Details mapStudentDetails(final Student student) {
return Details.builder()
.line1(student.getLine1())
.line2(student.getLine2())
.postcode(student.getPostcode())
.country(student.getCountryCode())
.build();
}
UPDATED Method 2 :
private Details mapTeacherDetails(final Teacher teacher) {
return Details.builder()
.line1(teacher.getAddressLine1())
.line2(teacher.getAddressLine2())
.postcode(teacher.getZipCode())
.country(teacher.getCountryCode())
.build();
}
How can I implement a generic method for this usecase ?
private Details mapDetails ( T type) {
}
Firstly, because you are using the same methods (getLine1(), getLine2(), getPostcode()) it's obvious that they are unrelated to the responsibilities of these classes and must reside somewhere else.
As far as these concerns are connected to postal service and don't related to the idiosyncratic responsibilities of the classes Student and Teacher they have to be externalized.
Let's group the behavior related to the post inside the interface PostDetails (sorry for a clumsy name). And I want to emphasize that it's highly advisable to use an interface for this purpose, not an abstract class like Person. Tomorrow you may wish to be able to send letters to the organizations but it doesn't make much sense for a class Campany to extend the class Person. Inheritance creates a tight coupling and can be easily misused. If you have a choice between an interface and abstract class in the class design interface takes precedence.
Methods of the PostDetails could be abstract or default (which will probably make sense because the procedure of sending letters except for special cases must be the same).
public interface PostDetails {
String getLine1();
String getLine2();
String getPostcode();
String getCountryCode();
}
Both Student and Teacher classes must implement the contract defined by the PostDetails.
public class Student implements PostDetails {
// implementation for Student
}
public class Teacher implements PostDetails {
// implementation for Teacher
}
As far as method mapDetails() isn't bound to any class and meant to use only behavior defined in the PostDetails it can accept any implementation of this interface (Student, Teacher, Company, etc).
private Details mapDetails(PostDetails postDetails) {
}
Update
If there's a need for two different sets of behavior related to postal service then it clearly has to be two interfaces (even if now you have only two classes this decision can bring benefits afterward). And as a consequence, there must be two overloaded versions of the mapDetails() method that accept as parameter instances of these interfaces.

Is this a correct implementation of the strategy pattern (JAVA, Fly method of ducks)?

I just want a quick lookover that I implemented the different fly strategies correctly.
The program simply consists of a duck class that uses an interface for its fly method. The interface has different implementations (namely SimpleFly and NoFly), and a switch statement chooses the correct method based on the specie enum.
As I understand, the strategy pattern is meant to avoid duplicate code between child classes at the same level, which decreases maintainability and extensibility. So instead we abstract out the related algorithms to interfaces and choose them as needed.
CODE:
package DesignPatterns;
//Here we will separate the fly method of ducks into implementations of an internface and then instantiate ducks with those attributes
interface IFly {
public void fly();
}
//These are called strategies
class SimpleFly implements IFly {
#Override
public void fly() {
System.out.println("Quack Quack i am flying in the air");
}
}
class NoFly implements IFly {
#Override
public void fly() {
System.out.println("I cannot fly.");
}
}
//Now the base class just has to implement one of these strategies
class Duck {
private IFly flyType;
public enum SPECIE {
WILD, CITY, RUBBER
}
public Duck(SPECIE specie) {
switch(specie) {
//Here just select the algorithms you want to assign to each type of DUCK. More flexible than horizontal code between species.
case WILD:
case CITY:
this.flyType = new SimpleFly();
break;
case RUBBER:
this.flyType = new NoFly();
break;
default:
//If a new enum is defined but no definition yet, this stops code from breaking
this.flyType = new SimpleFly();
}
}
public void fly() {
flyType.fly();
}
}
The output is correct as in this example:
Duck rubberDuck = new Duck(Duck.SPECIE.RUBBER);
Duck normalDuck = new Duck(Duck.SPECIE.WILD);
rubberDuck.fly();
normalDuck.fly();
Yields:
I cannot fly.
Quack Quack i am flying in the air
Thank you in advance and please let me know about any gaps in my knowledge,
Sshawarma
I would point out a couple issues of semantics and terminology.
It's confusing to have a method named fly that can be implemented as not flying. Naming the method tryToFly or documenting the method as merely an attempt are two ways of addressing this confusion. The software principle to reference here is Liskov Substitution.
The base class does not implement one of the strategies; rather, it composes a strategy. The purpose of the Strategy pattern is to avoid subclassing through composition.
To reiterate one of the comments, Duck should accept an instance of IFly directly in its constructor (or a setter method) rather than switching on an enum. Another goal of the Strategy pattern is to avoid branching logic.
The essence of the pattern is that you've avoided creating multiple subclasses of Duck by instead creating multiple implementations of IFly. This has the advantage that those IFly implementations can be reused without a complex inheritance hierarchy, e.g. WILD and CITY can share one strategy.
As mentioned in the comments, strategies also have the advantage that a Duck could change its strategy at runtime. For example, IFly might be implemented by Soar and Glide so that a Duck would switch between these different strategies depending on the wind.

Java class hierarchy refactoring without changing the invoking code, is it possible?

Current situation:
in a Java system, we have a class named Passenger as below, let's say,
public Class Passenger{
//lots of member fields
private String firstName ;
private String lastName ;
private WhatEverAttribute att;
//lots of getters & setters
WhatEverAttribute getAtt(){ return att;}
void setAtt(WhatEverAttribute attIn){ this.att=attIn;}
...
//and lots of methods,for example
List<String> doWhatEverFuction(...){ return ... }
...
}
And in the application elsewhere there are a many places will create and use this class as:
Passenger p1 = new Passenger();
p.setFirstName("blablabla")
p.setAtt(xxx);
Passenger p2 = new Passenger();
p2.setAtt(yyy)
List retl = p2.doWhatEverFuction(...);
...
The system previously only manage Air/Flight passengers, so the Passenger
class is actually data model for air passengers,
Now the problem is, we need to extend the model and make a hierarchy, as the Passenger will be a generic Passenger model, holding common fields and functions, new model AirPassenger and SeaPassenger will extend it:
enter image description here
So some common fields and functions will be kept
in Passenger to share between AirPassenger and SeaPassenger, but most air passenger specific fields and functions will be pushed down to AirPassenger,
then everybody knows that I have to change the existing code accessing Passenger from
Passenger p = new Passenger();
p.xxxxxx();
to
AirPassenger p = new AirPassenger();
p.xxxxxx();
There are so many places and I don't want to manually change them in many places in existing code accessing Passenger from the whole application,
What I want is after making the hierachy, the rest of the code still working without any changes, by utilizing some tricks of technics, I could return
an AirPassenger through the new Passenger() constructor like:
Passenger{
Passenger(){
return Passenger("Air")
}
Passenger(String type){
Switch(type){
...
case "Air": return new AirPassenger();
...
}
}
}
by some dynamic features of Java, CGLIB or whatever, is it possible?
The approach you end up choosing will depend on many factors, largely how and where your code is being used. If all usages of this class are accessible to you, I would highly advise against your proposed solution - a proper inheritance hierarchy would help keep your code organized and make it possible to easily expand your program in the future. Many IDEs (e.g IntelliJ) offer great functionality for smart-refactoring of your code and extraction to new classes, that will do almost all the work automatically and ensure the code keeps running as intended.
If possible, your situation is a classic case for the use of an abstract parent class. Since there is no such thing as a "general passenger", a more correct design for your hierarchy would be to declare Passenger as an abstract class. This way instances of Passenger cannot be created directly, but the class itself can hold implementations which inheriting classes can use or override as necessary.
You can also add a factory method to this class, which will return a new Passenger of the correct type, according to input (as you suggested).
Edit:
Polymorphism and class hierarchy work in Java in a very particular way. That is, some limitations are put on the programmer to maintain code readability and modularity.
What you have asked for (in your clarification comments) is not possible in the way you are describing.
You create two new classes:
class AirPassenger extends Passenger {
...
public void doSomethingAir() {
...
}
...
}
class SeaPassenger extends Passenger {
...
public void doSomethingSea() {
...
}
...
}
You refactor some of its methods into the new AirPassenger class and leave some where they are.
The first thing you will notice, is that you cannot use the existing Passenger constructor to return instances of AirPassenger or SeaPassenger, since a constructor is a
void method and has no return value. You will therefore need to provide some construction Factory method to create instances of either AirPassenger or SeaPassenger.
Passenger createPassenger(String passengerType) {
switch (passengerType) {
case "sea":
return new SeaPassenger();
default:
return new AirPassenger();
}
}
You refactored methods out of Passenger and into AirPassenger. These methods no longer exist in the Passenger class, and they cannot be called by Passenger objects.
You can however use explicit type casting to re-cast all Passenger objects to AirPassenger, and then you will be able to use all the methods which are now in AirPassenger.
This can also be done using a single method:
AirPassenger convertToAirPassenger(Passenger passenger) {
return (AirPassenger) passenger;
}
Of course I can find & replace, and most IDE can do it,
but problem is in the system there are some configuration file, and txt file, work as dictionary, and templates you know, they use the Passenger word or add prefix and suffix, or lower case, you know, you can not just find and replace, so not only Java code changes needs to be made, so I would rather not change them if there is a way, that is my question.
//you create an instance of class
ClassA obj = new ClassA();
//you call method doIT() inside ClassA
obj.doIt();
Now I have to re-model it as ClassA becomes a superclass, and those methods push down into its subclass, let's say ClassB, so ClassB extends ClassA, method doIt() is inside
ClassB now,
everyone knows as usual I need to change the above code to
//you create an instance of ClassB,
ClassB obj = new ClassB();
//or ClassB obj = new ClassA(); you have little code in the ClassA constuctor, etc.
//then you call a method
obj.doIt();
I know that, but my question is, without make changes to it
ClassA obj = new ClassA();
obj.doIt();
is there any tricks that will make it works with the new model?

Trouble understanding An excerpt from 'Effective Java' about compareTo

This is about the compareTo contract that classes can implement.
there is no way to extend an instantiable class with a new value
component while preserving the compareTo contract, unless you are
willing to forgo the benefits of object-oriented abstraction. The same
workaround applies, too. If you want to add a value component to a
class that implements Comparable, don’t extend it; write an unrelated
class containing an instance of the first class. Then provide a “view”
method that returns this instance. This frees you to implement
whatever compareTo method you like on the second class, while allowing
its client to view an instance of the second class as an instance of
the first class when needed.
I have read Why can't I extend an instantiable class with a new value component while preserving the compareTo contract?. It helped answer one or two questions i had.But the below question still remains unanswered to me.
1) If i define the two classes as unrelated,i am free to implement the compareTo method as i want.Agree that.But how am i making the two classes have the is-a/parent-child relationship.Can someone explain whatever Joshua called the "view" method?
Can someone explain whatever Joshua called the "view" method?
I will continue Jon Skeet's simple example from the answer that you linked in your post:
// In Jon's code, Person derives from NamedThing
class NamedThing {
String name;
}
class Person extends NamedThing {
Date dateOfBirth;
}
"Providing a view" rather than "extending" would mean designing your class hierarchy like this:
class NamedThing {
String name;
}
class Person {
private NamedThing namedThing;
// Here is the view method
public NamedThing asNamedThing() {
return namedThing;
}
// Here is a convenience method for accessing name directly
public String getName() {
return namedThing.name;
}
Date dateOfBirth;
}
This frees you up to implement a new compareTo inside the Person, because there is no requirement to stay compatible with the superclass. If you need to view your person as a NamedThing, call asNamedThing() to get a view of the person reduced to a thing with a name.
Note that since this is not an is-a relationship, the asNamedThing is somewhat misleading: you get the named thing inside the person, not the person who happens to be a named thing. This limits the applicability of compareTo: for example, you cannot sort persons among other NamedThings.

Difference between Inheritance and Composition

Are Composition and Inheritance the same?
If I want to implement the composition pattern, how can I do that in Java?
They are absolutely different. Inheritance is an "is-a" relationship. Composition is a "has-a".
You do composition by having an instance of another class C as a field of your class, instead of extending C. A good example where composition would've been a lot better than inheritance is java.util.Stack, which currently extends java.util.Vector. This is now considered a blunder. A stack "is-NOT-a" vector; you should not be allowed to insert and remove elements arbitrarily. It should've been composition instead.
Unfortunately it's too late to rectify this design mistake, since changing the inheritance hierarchy now would break compatibility with existing code. Had Stack used composition instead of inheritance, it can always be modified to use another data structure without violating the API.
I highly recommend Josh Bloch's book Effective Java 2nd Edition
Item 16: Favor composition over inheritance
Item 17: Design and document for inheritance or else prohibit it
Good object-oriented design is not about liberally extending existing classes. Your first instinct should be to compose instead.
See also:
Composition versus Inheritance: A Comparative Look at Two Fundamental Ways to Relate Classes
Composition means HAS A
Inheritance means IS A
Example: Car has a Engine and Car is a Automobile
In programming this is represented as:
class Engine {} // The Engine class.
class Automobile {} // Automobile class which is parent to Car class.
class Car extends Automobile { // Car is an Automobile, so Car class extends Automobile class.
private Engine engine; // Car has an Engine so, Car class has an instance of Engine class as its member.
}
How inheritance can be dangerous ?
Lets take an example
public class X{
public void do(){
}
}
Public Class Y extends X{
public void work(){
do();
}
}
1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature
public int work(){
}
Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.
How does composition solves this issue?
Lets see by revising the same example
public class X{
public void do(){
}
}
Public Class Y{
X x = new X();
public void work(){
x.do();
}
}
Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class.
Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.
2) Second very good advantage of composition in that It provides method calling flexibility, for example :
class X implements R
{}
class Y implements R
{}
public class Test{
R r;
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance
3) Another great advantage : Unit testing
public class X {
public void do(){
}
}
Public Class Y {
X x = new X();
public void work(){
x.do();
}
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.
4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.
Lets take an example to understand this :
Public class Transaction {
Banking b;
public static void main(String a[])
{
b = new Deposit();
if(b.deposit()){
b = new Credit();
c.credit();
}
}
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time
composition is also know as HAS-A relation and inheritance is also known as IS-A relation
So make it a habit of always preferring composition over inheritance for various above reasons.
The answer given by #Michael Rodrigues is not correct (I apologize; I'm not able to comment directly), and could lead to some confusion.
Interface implementation is a form of inheritance... when you implement an interface, you're not only inheriting all the constants, you are committing your object to be of the type specified by the interface; it's still an "is-a" relationship. If a car implements Fillable, the car "is-a" Fillable, and can be used in your code wherever you would use a Fillable.
Composition is fundamentally different from inheritance. When you use composition, you are (as the other answers note) making a "has-a" relationship between two objects, as opposed to the "is-a" relationship that you make when you use inheritance.
So, from the car examples in the other questions, if I wanted to say that a car "has-a" gas tank, I would use composition, as follows:
public class Car {
private GasTank myCarsGasTank;
}
Hopefully that clears up any misunderstanding.
Inheritance brings out IS-A relation. Composition brings out HAS-A relation.
Strategy pattern explain that Composition should be used in cases where there are families of algorithms defining a particular behaviour.Classic example being of a duck class which implements a flying behaviour.
public interface Flyable{
public void fly();
}
public class Duck {
Flyable fly;
public Duck(){
fly = new BackwardFlying();
}
}
Thus we can have multiple classes which implement flying
eg:
public class BackwardFlying implements Flyable{
public void fly(){
Systemout.println("Flies backward ");
}
}
public class FastFlying implements Flyable{
public void fly(){
Systemout.println("Flies 100 miles/sec");
}
}
Had it been for inheritance, we would have two different classes of birds which implement the fly function over and over again. So inheritance and composition are completely different.
Composition is just as it sounds - you create an object by plugging in parts.
EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (objectToFill.percentageFull() <= 100) {
objectToFill.AddSomeFuel();
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
Are Composition and Inheritance the same?
They are not same.
Composition : It enables a group of objects have to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies
Inheritance: A class inherits fields and methods from all its superclasses, whether direct or indirect. A subclass can override methods that it inherits, or it can hide fields or methods that it inherits.
If I want to implement the composition pattern, how can I do that in Java?
Wikipedia article is good enough to implement composite pattern in java.
Key Participants:
Component:
Is the abstraction for all components, including composite ones
Declares the interface for objects in the composition
Leaf:
Represents leaf objects in the composition
Implements all Component methods
Composite:
Represents a composite Component (component having children)
Implements methods to manipulate children
Implements all Component methods, generally by delegating them to its children
Code example to understand Composite pattern:
import java.util.List;
import java.util.ArrayList;
interface Part{
public double getPrice();
public String getName();
}
class Engine implements Part{
String name;
double price;
public Engine(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Trunk implements Part{
String name;
double price;
public Trunk(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Body implements Part{
String name;
double price;
public Body(String name,double price){
this.name = name;
this.price = price;
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
}
class Car implements Part{
List<Part> parts;
String name;
public Car(String name){
this.name = name;
parts = new ArrayList<Part>();
}
public void addPart(Part part){
parts.add(part);
}
public String getName(){
return name;
}
public String getPartNames(){
StringBuilder sb = new StringBuilder();
for ( Part part: parts){
sb.append(part.getName()).append(" ");
}
return sb.toString();
}
public double getPrice(){
double price = 0;
for ( Part part: parts){
price += part.getPrice();
}
return price;
}
}
public class CompositeDemo{
public static void main(String args[]){
Part engine = new Engine("DiselEngine",15000);
Part trunk = new Trunk("Trunk",10000);
Part body = new Body("Body",12000);
Car car = new Car("Innova");
car.addPart(engine);
car.addPart(trunk);
car.addPart(body);
double price = car.getPrice();
System.out.println("Car name:"+car.getName());
System.out.println("Car parts:"+car.getPartNames());
System.out.println("Car price:"+car.getPrice());
}
}
output:
Car name:Innova
Car parts:DiselEngine Trunk Body
Car price:37000.0
Explanation:
Part is a leaf
Car contains many Parts
Different Parts of the car have been added to Car
The price of Car = sum of ( Price of each Part )
Refer to below question for Pros and Cons of Composition and Inheritance.
Prefer composition over inheritance?
as another example, consider a car class, this would be a good use of composition, a car would "have" an engine, a transmission, tires, seats, etc. It would not extend any of those classes.
Composition is where something is made up of distinct parts and it has a strong relationship with those parts. If the main part dies so do the others, they cannot have a life of their own. A rough example is the human body. Take out the heart and all the other parts die away.
Inheritance is where you just take something that already exists and use it. There is no strong relationship. A person could inherit his fathers estate but he can do without it.
I don't know Java so I cannot provide an example but I can provide an explanation of the concepts.
In Simple Word Aggregation means Has A Relationship ..
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
Why Use Aggregation
Code Reusability
When Use Aggregation
Code reuse is also best achieved by aggregation when there is no is a Relation ship
Inheritance
Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
Using inheritance in Java
1 Code Reusability.
2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).
Inheritance between two classes, where one class extends another class establishes "IS A" relationship.
Composition on the other end contains an instance of another class in your class establishes "Has A" relationship. Composition in java is is useful since it technically facilitates multiple inheritance.
Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Another difference which comes from this fact is that by using Composition you can reuse code for even final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition you can reuse code from many classes as they are declared as just a member variable, but with Inheritance you can reuse code form just one class because in Java you can only extend one class, because multiple Inheritance is not supported in Java. You can do this in C++ though because there one class can extend more than one class. BTW, You should always prefer Composition over Inheritance in Java, its not just me but even Joshua Bloch has suggested in his book
I think this example explains clearly the differences between inheritance and composition.
In this exmple, the problem is solved using inheritance and composition. The author pays attention to the fact that ; in inheritance, a change in superclass might cause problems in derived class, that inherit it.
There you can also see the difference in representation when you use a UML for inheritance or composition.
http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html
Inheritances Vs Composition.
Inheritances and composition both are used to re-usability and extension of class behavior.
Inheritances mainly use in a family algorithm programming model such as IS-A relation type means similar kind of object. Example.
Duster is a Car
Safari is a Car
These are belongs to Car family.
Composition represents HAS-A relationship Type.It shows the ability of an object such as Duster has Five Gears , Safari has four Gears etc. Whenever we need to extend the ability of an existing class then use composition.Example we need to add one more gear in Duster object then we have to create one more gear object and compose it to the duster object.
We should not make the changes in base class until/unless all the derived classes needed those functionality.For this scenario we should use Composition.Such as
class A Derived by Class B
Class A Derived by Class C
Class A Derived by Class D.
When we add any functionality in class A then it is available to all sub classes even when Class C and D don't required those functionality.For this scenario we need to create a separate class for those functionality and compose it to the required class(here is class B).
Below is the example:
// This is a base class
public abstract class Car
{
//Define prototype
public abstract void color();
public void Gear() {
Console.WriteLine("Car has a four Gear");
}
}
// Here is the use of inheritence
// This Desire class have four gears.
// But we need to add one more gear that is Neutral gear.
public class Desire : Car
{
Neutral obj = null;
public Desire()
{
// Here we are incorporating neutral gear(It is the use of composition).
// Now this class would have five gear.
obj = new Neutral();
obj.NeutralGear();
}
public override void color()
{
Console.WriteLine("This is a white color car");
}
}
// This Safari class have four gears and it is not required the neutral
// gear and hence we don't need to compose here.
public class Safari :Car{
public Safari()
{ }
public override void color()
{
Console.WriteLine("This is a red color car");
}
}
// This class represents the neutral gear and it would be used as a composition.
public class Neutral {
public void NeutralGear() {
Console.WriteLine("This is a Neutral Gear");
}
}
Composition means creating an object to a class which has relation with that particular class.
Suppose Student has relation with Accounts;
An Inheritance is, this is the previous class with the extended feature. That means this new class is the Old class with some extended feature.
Suppose Student is Student but All Students are Human. So there is a relationship with student and human. This is Inheritance.
Inheritence means reusing the complete functionality of a class, Here my class have to use all the methods of the super class and my class will be titely coupled with the super class and code will be duplicated in both the classes in case of inheritence.
But we can overcome from all these problem when we use composition to talk with another class . composition is declaring an attribute of another class into my class to which we want to talk. and what functionality we want from that class we can get by using that attribute.
No , Both are different . Composition follow "HAS-A" relationship and inheritance follow "IS-A" relationship . Best Example for composition was Strategic pattern .

Categories

Resources