Difference between Inheritance and Composition - java

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 .

Related

Is there a better way to create an abstract class that extends another abstract class and adds new features?

I have an abstract class that has a concrete method solveand several abstract methods that are used by solve:
public abstract class A{
public void solve(){
//code for solve
}
public abstract void a();
public abstract void b();
}
Then I have another class B that extends A, reimplements the solve methods using the abstract methods from A and new ones added (c,d). It also has a boolean field that indicates if it has to use the solve A or the one from B.
public abstract class B extends A{
boolean useA;
public B(boolean useA){
this.useA = useA
}
public void solve(){
if(useA) super.solve();
else // code for solve
}
public abstract void c();
public abstract void d();
}
Then I have a concrete class C that extends B, implements all methods and has a boolean to indicate if solve has to be used or not.
public class C extends B{
public C(boolean useA){
super(useA);
}
... //code for a,b,c and d
}
Is there any way to do this better? I think that maybe it's not following the principles of OOP.
Some already mentioned the decorator pattern, and there is the strategy pattern too.
However one might use lambdas for injecting some handlers.
Handlers might be done using public service / protected requirement:
class A {
public final f() {
...
onF(x, y);
}
protected abstract void onF(X x, Y y);
}
Solution complexes often are better of without inheritance, but as field, delegating to a field.
In that the answer of #LonelyNeuron gives good arguments.
In short: when in doubt, code it out first, and refactor it to some elegant model. Separating concerns and such.
The problem is, that the best solution for OOP is sometimes heavily over-engineered. So in some cases the solution which takes the least amount of work will be the best.
Also it is really hard to judge in this case. While it is good that you tried to create a Minimal, Complete, and Verifiable example, it lacks the most important information about what should inherit what: the purpose of each class. You could for example imagine that it might make sense to split your class B into two, where one does and the other doesn't override solve(), but if that is a good idea can only be decided to ask the right questions about the purpose of each class.
I suspect that you are asking these questions because you want to know the best way to reuse code in your classes. If that is the case: don't. Taken from this wikipedia article:
In most quarters, class inheritance for the sole purpose of code reuse has fallen out of favor. The primary concern is that implementation inheritance does not provide any assurance of polymorphic substitutability—an instance of the reusing class cannot necessarily be substituted for an instance of the inherited class. An alternative technique, explicit delegation, requires more programming effort, but avoids the substitutability issue. In C++ private inheritance can be used as a form of implementation inheritance without substitutability. Whereas public inheritance represents an "is-a" relationship and delegation represents a "has-a" relationship, private (and protected) inheritance can be thought of as an "is implemented in terms of" relationship.

How can a child interface reuse its parents' implementations?

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.

Interfaces and Abstract classes confusion in Java with examples

I'm having trouble understanding when to use an interface as opposed to an abstract class and vice versa. Also, I am confused when to extend an interface with another interface. Sorry about the long post, but this is very confusing.
Creating shapes seems like a popular starting point. Let's say we want a way to model 2D shapes. We know that each shape will have an area. What would be the difference between the following two implementations:
with interfaces:
public interface Shape {
public double area();
}
public class Square implements Shape{
private int length = 5;
public Square(){...}
public double area()
return length * length;
}
}
with abstract class:
abstract class Shape {
abstract public double area();
}
public class Square extends Shape {
private length = 5;
public Square(){...}
public double area(){
return length * length;
}
I understand that abstract classes allows you to define instance variables and allows you to give method implementations whereas an interface cannot do these things. But in this case, it seems like these two implementations are identical. So using any one is fine?
But now say we want to describe different types of triangles. We can have an isosceles, acute, and right angle triangles. To me, it makes sense to use class inheritance in this case. Using the 'IS-A' definition: a Right Triangle "IS-A" Triangle. A Triangle "IS-A" Shape. Also, an abstract class should define behaviors and attributes that are common within all subclasses, so this is perfect:
with abstract class
abstract Triangle extends Shape {
private final int sides = 3;
}
class RightTriangle extends Triangle {
private int base = 4;
private int height = 5;
public RightTriangle(){...}
public double area() {
return .5 * base * height
}
}
We can do this with interfaces as well, with Triangle and Shape being interfaces. However, unlike class inheritance (using 'IS-A' relationship to define what should be a subclass), I'm not sure how to use an interface. I see two ways:
First way:
public interface Triangle {
public final int sides = 3;
}
public class RightTriangle implements Triangle, Shape {
private int base = 4;
private int height = 5;
public RightTriangle(){}
public double area(){
return .5 * height * base;
}
}
Second way:
public interface Triangle extends Shape {
public final int sides = 3;
}
public class RightTriangle implements Triangle {
....
public double area(){
return .5 * height * base;
}
}
It seems to me like both of these ways work. But when would you use one way over the other? And are there any advantages to using interfaces over abstract classes to represent different triangles? Even though we complicated the description of a shape, using interface vs abstract class still seem equivalent.
A critical component to interfaces is that it can define behaviors that can be shared across unrelated classes. So an interface Flyable would be present in classes Airplane as well as in Bird. So in this case, it is clear that an interface approach is preferred.
Also, to build off of the confusing interface extending another interface:
When should the 'IS-A' relationship be ignored when deciding on what should be an interface?
Take this example: LINK.
Why should 'VeryBadVampire' be a class and 'Vampire' be an interface? A 'VeryBadVampire' IS-A 'Vampire', so my understanding is that a 'Vampire' should be a superclass (maybe abstract class). A 'Vampire' class can implement 'Lethal' to keep its lethal behavior. Furthermore, a 'Vampire' IS-A 'Monster', so 'Monster' should be a class as well. A 'Vampire' class can also implement an interface called 'Dangerous' to keep its dangerous behavior. If we wish to create a new monster called 'BigRat' which is dangerous but not lethal, then we can create a 'BigRat' class which extends 'Monster' and implements 'Dangerous'.
Wouldn't the above achieve the same output as using 'Vampire' as an interface (described in the link)? The only difference I see is that using class inheritance and preserving the 'IS-A' relationship clears up a lot of confusion. Yet this is not followed. What is the advantage of doing this?
Even if you wanted a monster to share vampiric behavior, one can always redefine how the objects are represented. If we wanted a new type of vampire monster called 'VeryMildVampire' and we wanted to create a vampire-like monster called 'Chupacabra', we can do this:
'Vampire' class extends 'Monster' implements 'Dangerous', 'Lethal', 'BloodSuckable'
'VeryMildVampire' class extends 'Vampire' class
'Chupacabra' class extends 'Monster' implements 'BloodSuckable'
But we can also do this:
'VeryMildVampire' extends 'Monster' implements Dangerous, Lethal, Vampiric
'Chupacabra' extends 'Monster' implements Dangerous, Vampiric
The second way here creates a 'Vampiric' interface so that we can more easily define a related monster rather than create a bunch of interfaces which define vampiric behaviors (like in the first example). But this breaks the IS-A relationship. So I'm confused...
Remember the basic concept when using abstract classes or interfaces.
Abstract classes are used when class to extended is more closely coupled to the class implementing it, i.e when both have a parent-child relation.
In example:
abstract class Dog {}
class Breed1 extends Dog {}
class Breed2 extends Dog {}
Breed1 and Breed2 are both types of a dog and has some common behavior as a dog.
Whereas, an interface is used when implementing class has a feature it can take from the class to implemented.
interface Animal {
void eat();
void noise();
}
class Tiger implements Animal {}
class Dog implements Animal {}
Tiger and Dog are two different category but both eat and make noises ,which are different. So they can use eat and noise from Animal.
Use an abstract class when you want to make one or more methods not abstract.
If you want to keep all abstract, use an interface.
This is question that will come to when designing class hierarchies that are bit complicated that normal. But generally there are few things you need to know when using abstract classes and interfaces
Abstract Class
Allows you to leverage the power of using constructors and constructor overriding
Restrict the class having multiple inheritance(This is particularly useful if you are designing a complicated API)
Instance variables and method implementations
Leverage the power of method super calling(Use super to call the parent abstract class's implementation)
Interface
Enables multiple inheritance - you can implement n number of interfaces
Allows to represent only conceptual methods (No method bodies)
Generally use Interfaces for '-able' clause(as in functionality).
Eg:-
Runnable
Observable
Use abstract classes for something like is-a(evolution format).
Eg:-
Number
Graphics
But hard and fast rules are not easy to create. Hope this helps
You have quite a few questions here. But I think basically you are asking about interface vs. abstract class.
With interfaces, you can have classes that implement multiple interfaces. However, interface is not durable if you want to use it as the API. Once the interface is published, it's hard to modify the interface because it will break other people's codes.
With abstract class, you can only extends one class. However, abstract class is durable for API because you can still modify in later versions without breaking other people's code. Also with abstract class, you can have predefined implementation. For example, in your Triangle example, for abstract class, you may have a method countEdges() which returns 3 by default.
This is a question that comes up very often, yet there is no single "right" answer that will please everyone.
Classes represent is-a relationships and interfaces represent can-do behaviour. I usually go by a few empirical rules:
Stick with a class (abstract/concrete) unless you are certain that you need an interface.
If you do use interfaces, slice them into very specific functionality. If an interface contains more than a few methods, you're doing it wrong.
Further, most examples of shapes and persons (or vampires for that matter!) are usually poor examples of real-world models. The "right" answer depends on what your application requires. For instance, you mentioned:
class Vampire extends Monster implements Dangerous, Lethal, BloodSuckable
Does your application really need all these interfaces? How many different types of Monsters are there? Do you actually have classes other than Vampire that implement BloodSuckable?
Try not to generalize too much and extract interfaces when you have no need for them. This goes back to the rule of thumb: stick with a simple class unless your use case demands an interface.
This is a good question. There are many good and bad answers for this question. Typical question is, what is the difference between an abstract class an interface? Lets see where you use abstract classes and where you use interface.
Where to use abstract classes:
In terms of OOP, If there is an inheritance hierarchy then you should use an abstract class to model your design.
Where to use interfaces:
When you have to connect different contracts(non related classes) using one common contract then you should use an interface. Lets take Collection framework as an example.
Queue,List,Set have different structures from their implementation.But still they share some common behaviors like add(),remove(). So we can create an interface called Collection and the we have declared common behaviors in the interface. As you see, ArrayList implements all the behaviors from both List and RandomAccess interfaces.Doing so we can easily add new contracts without changing the existing logic. This is called as "coding to an interface".
Your shape example is good. I look at it this way:
You only have abstract classes when you have methods or member variables that are shared. For your example for Shape you've only got a single, unimplemented method. In that case always use an interface.
Say you had an Animal class. Each Animal keeps track of how many limbs it has.
public abstract class Animal
{
private int limbs;
public Animal(int limbs)
{
this.limbs = limbs;
}
public int getLimbCount()
{
return this.limbs;
}
public abstract String makeNoise();
}
Because we need to keep track of how many limbs each animal has, it makes sense to have the member variable in the superclass. But each animal makes a different type of noise.
So we need to make it an abstract class as we have member variables and implemented methods as well as abstract methods.
For your second question, you need to ask yourself this.
Is a Triangle always going to be a shape?
If so, you need to have Triangle extend from the Shape interface.
So in conclusion - with your first set of code examples, choose the interface. With the last set, choose the second way.

Java generics problem

I'm working on a project where I am trying to use generics but I'm having a hard time.
Say I have a many cars, all of them implemented in a different class (eg. audi.java, toyota.java, etc..) and each of them have a method called startCar(). Now I want to create a class Cars that lets other classes use these cars. However the following will not work. How should I go about implementing it?
public class Cars {
private MyCar mycar;
private class MyCar <MySpecificBrandOfCar>{
private MySpeicifBrand mySpecifcCar;
public MyCar(){}
}
public Cars(){
myCar = new myCar<audi>;
}
..other methods..
}
I also tried creating an interface, but that gave errors too.
Thanks
EDIT, attempted nfechner's suggestion
Thanks for all the responses!
Would the following work (NB:GenericCar is an interface that is implemented by all cars (eg. audi.java) and has functions such as startCar()
public class Car{
private GenericCar mycar;
public Car(){
mycar = new audi();
}
}
Generics can't be used to instantiate a class unfortunately, not in Java. Perhaps you could be a bit more specific about your intention, but you might find it useful to have some base class Car and have each specific car extend it. If you define the startCar() method in the base class Car, every subtype of Car will also have this method through polymorphism.
public class Car{
public void startCar(){ }
}
public class Audi extends Car{}
public class Toyota extends Car{}
and so on.
Your code looks a bit overengineered. What's wrong with a simple Car interface, that all car types implement?
In this example Inheritance and Polymorphism will be a better solution than Generics.
Check this example. Java Tutorial - Inheritance and Polymorphism
You should not use generics here. (Think of them as type-parameters you do not want to fix, e.g. as for Collection).
If cars of different brands do behave differently, do inheritance instead, like Jonathan suggests.
But a better design is using composition instead of inheritance, i.e. Cars have a field of the class Brand. This is especially the case if the behavior is not strongly influenced. And I don't think an Audi behaves that much different from a Toyota.
Furthermore, I don't think there are that many brands, and you probably only need one instance of each brand. So use an enum instead of a class for Brand. In detail:
public class Car {
public static enum Brand { Audi, Toyota };
private Brand brand;
public Cars(Brand brandParam){
this.brand = brandParam;
}
//..other methods, getter and setter for brand
}
You can put methods in the Brand enum for the small and specific varying behavior. I think Josh Bloch, the author of Java Enums, explains their capabilities very well in Effective Java, 2nd edition.
Finally, try to choose better names for your classes and variables (I don't think MyCar is telling you anything).
This is not a circumstance where using generics is appropriate. You should use an interface or a superclass. I'm not sure what errors you were seeing with an interface, but it would be easier to fix them than to try to fix your problems with this approach.

How can interfaces replace the need for multiple inheritance when have existing classes

First of all... Sorry for this post. I know that there are many many posts on stackoverflow which are discussing multiple inheritance. But I already know that Java does not support multiple inheritance and I know that using interfaces should be an alternative. But I don't get it and see my dilemma:
I have to make changes on a very very large and complex tool written in Java. In this tool there is a data structure built with many different class objects with a linked member hierarchy. Anyway...
I have one class Tagged which has multiple methods and returns an object tag depending on the object's class. It needs members and static variables.
And a second class called XMLElement allows to link objects and in the end generate a XML file. I also need member and static variables here.
Finally, I have these many many data classes which nearly all should extend XMLElement and some of them Tagged.
Ok ok, this won't work since it's only possible to extend just one class. I read very often that everything with Java is ok and there is no need for having multiple inheritance. I believe, but I don't see how an interface should replace inheritance.
It makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think).
I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.
I really don't get it so please can somebody explain me how to handle this?
Actually, I have no good answer other than Java SHOULD have Multiple Inheritance. The whole point that interfaces should be able to replace the need for Multiple Inheritance is like the big lie that when repeated enough times becomes true.
The argument is that Multiple Inheritance causes all these problems (la-di-dah), yet I keep hearing those arguments from Java developers who have never used C++. I also don't EVER remember C++ programmers saying "Gee, I love C++, but if they would only get rid of Multiple Inheritance, it would become a great language". People used it when it was practical and didn't when it wasn't.
Your problem is a classic case of where Multiple Inheritance would be appropriate. Any suggestion to refactor the code is really telling you how to work around the PROBLEM that Java has no Multiple Inheritance.
Also all the discussion that "oh, delegation is better, la-di-dah" is confusing religion with design. There is no right way. Things are either more useful or less useful and that is all.
In your case Multiple Inheritance would be more useful and a more elegant solution.
As far as refactoring your code into a less useful form to satisfy all the religious people who have never used Multiple Inheritance and believe "Multiple Inheritance is bad", I guess you will have to downgrade your code because I don't see Java "improving" in that way any time soon. There are too many people repeating the religious mantra to the point of stupidity that I can't see it ever being added to the language.
Actually, my solution for you would be "x extends Tagged, XMLElement" and that would be all.
...but as you can see from the solutions provided above, most people think that such a solution would be WAY TOO COMPLEX AND CONFUSING!
I would prefer to venture into the "x extends a,b" territory myself, even if it is a very frightening solution that might overwhelm the abilities of most Java programmers.
What is even more amazing about the solutions suggested above is that everyone here who suggested that you refactor your code into "delegation" because Multiple Inheritance is bad, would, if they were confronted with the very same problem, would solve the problem by simply doing: "x extends a,b" and be done with it, and all their religious arguments about "delegation vs inheritance" would disappear. The whole debate is stupid, and it only being advanced by clueless programmers who only demonstrate how well they can recite out of a book and how little they can think for themselves.
You are 100% correct that Multiple Inheritance would help, and no, you are doing anything wrong in your code if you think Java should have it.
You should probably favor composition (and delegation) over inheritance :
public interface TaggedInterface {
void foo();
}
public interface XMLElementInterface {
void bar();
}
public class Tagged implements TaggedInterface {
// ...
}
public class XMLElement implements XMLElementInterface {
// ...
}
public class TaggedXmlElement implements TaggedInterface, XMLElementInterface {
private TaggedInterface tagged;
private XMLElementInterface xmlElement;
public TaggedXmlElement(TaggedInterface tagged, XMLElementInterface xmlElement) {
this.tagged = tagged;
this.xmlElement = xmlElement;
}
public void foo() {
this.tagged.foo();
}
public void bar() {
this.xmlElement.bar();
}
public static void main(String[] args) {
TaggedXmlElement t = new TaggedXmlElement(new Tagged(), new XMLElement());
t.foo();
t.bar();
}
}
Similar to what Andreas_D suggested but with the use of inner classes. This way you indeed extend each class and can override it in your own code if desired.
interface IBird {
public void layEgg();
}
interface IMammal {
public void giveMilk();
}
class Bird implements IBird {
public void layEgg() {
System.out.println("Laying eggs...");
}
}
class Mammal implements IMammal {
public void giveMilk() {
System.out.println("Giving milk...");
}
}
class Platypus implements IMammal, IBird {
private class LayingEggAnimal extends Bird {}
private class GivingMilkAnimal extends Mammal {}
private LayingEggAnimal layingEggAnimal = new LayingEggAnimal();
private GivingMilkAnimal givingMilkAnimal = new GivingMilkAnimal();
#Override
public void layEgg() {
layingEggAnimal.layEgg();
}
#Override
public void giveMilk() {
givingMilkAnimal.giveMilk();
}
}
First it makes no sense to put the real implementation in all data classes since it is the same every time but this would be necessary with interfaces (I think).
How about using aggregation for the tags?
Rename your Tagged class to Tags.
Create a Tagged interface:
interface Tagged {
Tags getTags();
}
Let each class that needs to be "tagged", implement Tagged and let it have a tags field, which is returned from getTags.
Second I don't see how I could change one of my inheritance classes to an interface. I have variables in here and they have to be exactly there.
That's right, interfaces can't have instance variables. The data structures storing the tags however, shouldn't necessarily IMO be part of the classes that are tagged. Factor out the tags in a separate data structure.
I'd solve it that way: extract interfaces for the Tagged and XMLElement class (maybe you don't need all methods in the public interface). Then, implement both interfaces and the implementing class has a Tagged (your actual concrete Tagged class) and an XMLElement (your actual concrete XMLElement class):
public class MyClass implements Tagged, XMLElement {
private Tagged tagged;
private XMLElement xmlElement;
public MyClass(/*...*/) {
tagged = new TaggedImpl();
xmlElement = new XMLElementImpl();
}
#Override
public void someTaggedMethod() {
tagged.someTaggedMethod();
}
}
public class TaggedImpl implements Tagged {
#Override
public void someTaggedMethod() {
// so what has to be done
}
}
public interface Tagged {
public void someTaggedMethod();
}
(and the same for XMLElement)
one possible way;
1- You can create base class(es) for common functionality, make it abstract if you dont need to instantiate it.
2- Create interfaces and implement those interfaces in those base class(es). If specific implementation is needed, make the method abstract. each concrete class can have its own impl.
3- extend the abstract base class for in concrete class(es) and implement specific interfaces at this level as well
Just wondering if one could not simply use inner (member) classes (LRM 5.3.7)?
E.g. like this (based on the first answer above):
// original classes:
public class Tagged {
// ...
}
public class XMLElement {
// ...
}
public class TaggedXmlElement {
public/protected/private (static?) class InnerTagged extends Tagged {
// ...
}
public/protected/private (static?) class InnerXmlElement extends XMLElement {
// ...
}
}
This way you have a class TaggedXmlElement which actually contains all elements from the two original classes and within TaggedXmlElement you have access to non-private members of the member classes. Of course one would not use "super", but call member class methods.
Alternatively one could extend one of the classes and make the other a member class.
There are some restrictions, but I think they can all be worked around.
Well using Interface and single base class you are simply stating:
A) One object can be of only one type (Which is true in real life if you think ,
A pigeon is a bird, a toyota is a car , etc .. A pigeon is also an animal but every bird is animal anyway, so its hierarchically above the bird type -And in your OOP design Animal class should be base of Bird class in case you need to represent it -)
and
B) can do many different things (A bird can sing, can fly . A car can run , can stop ,etc..) which also fits the real life objects.
In a world where objects can be of multiple types (horizontally)
Let's say a a dolphin is a mammal and also a sea animal, in this case multiple inheritance would make more sense. It would be easier to represent it using multiple inheritance.
Using composition would be the way to go as another developer suggested. The main argument against multiple inheritance is the ambiguity created when you're extending from two classes with the same method declaration (same method name & parameters). Personally, however, I think that's a load of crap. A compilation error could easily be thrown in this situation, which wouldn't be much different from defining multiple methods of the same name in a single class. Something like the following code snippet could easily solve this dilema:
public MyExtendedClass extends ClassA, ClassB {
public duplicateMethodName() {
return ClassA.duplicateMethodName();
}
}
Another argument against multiple inheritance is that Java was trying to keep things simple so that amateur developers don't create a web of interdependent classes that could create a messy, confusing software system. But as you see in your case, it also complicates and confuses things when it's not available. Plus, that argument could be used for a 100 other things in coding, which is why development teams have code reviews, style checking software, and nightly builds.
In your particular situation though, you'll have to settle with composition (see Shojaei Baghini's answer). It adds a bit of boiler plate code, but it emulates the same behavior as multiple inheritance.
I run in a similar problem on Android. I needed to extend a Button and a TextView (both inheriting from View) with additional functions. Due to not having access to their super class, I needed to find another solution. I´ve written a new class which encapsulates all the implementations:
class YourButton extends Button implements YourFunctionSet {
private Modifier modifier;
public YourButton(Context context) {
super(context);
modifier = new Modifier(this);
}
public YourButton(Context context, AttributeSet attrs) {
super(context, attrs);
modifier = new Modifier(this);
}
public YourButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
modifier = new Modifier(this);
}
#Override
public void generateRandomBackgroundColor() {
modifier.generateRandomBackgroundColor();
}
}
class Modifier implements YourFunctionSet {
private View view;
public Modifier(View view) {
this.view = view;
}
#Override
public void generateRandomBackgroundColor() {
/**
* Your shared code
*
* ......
*
* view.setBackgroundColor(randomColor);
*/
}
}
interface YourFunctionSet {
void generateRandomBackgroundColor();
}
The problem here is, your classes need the same super class. You can also try to use different classes, but check which type it is from, for example
public class Modifier{
private View view;
private AnotherClass anotherClass;
public Modifier(Object object) {
if (object instanceof View) {
this.view = (View) object;
} else if (object instanceof AnotherClass) {
this.anotherClass = (AnotherClass) object;
}
}
public void generateRandomBackgroundColor(){
if(view!=null){
//...do
}else if(anotherClass!=null){
//...do
}
}
}
So here is basically my Modifier class the class which encapsulates all implementations.
Hope this helps someone.

Categories

Resources