SOLID and multiple inheritance - multiple-inheritance

I was thinking about languages that allow multiple inheritance like Python. How does SOLID apply to these languages?
It is often claimed that languages that allow multiple inheritance don't need interfaces. But what about type hinting?
If I define my method like this, I still have a hard dependency.
Therefor the Open closed principle cannot be applied, unless I extend a new class on the base class.
Why would I bother about a possible implementation someone wrote years ago and I want to be completely separated from that code by creating a new instance.
public function test(MyConcreteDependency $test){}
Is it true that interface based languages are cleaner for programming SOLID?

Related

What impact does using these facilities have on orthogonality?

I am reading The Pragmatic Programmer: From Journeyman to Master by Andrew Hunt, David Thomas. When I was reading about a term called orthogonality I was thinking that I am getting it right. I was understanding it very well. However, at the end of the chapter a few questions were asked to measure the level of understanding of the subject. While I was trying to answer those questions to myself I realized that I haven't understood it perfectly. So to clarify my understandings I am asking those questions here.
C++ supports multiple inheritance, and Java allows a class to
implement multiple interfaces. What impact does using these facilities
have on orthogonality? Is there a difference in impact between using multiple
inheritance and multiple interfaces?
There are actually three questions bundled up here: (1) What is the impact of supporting multiple inheritance on orthogonality? (2) What is the impact of implementing multiple interfaces on orthogonality? (3) What is the difference between the two sorts of impact?
Firstly, let us get to grips with orthogonality. In The Art of Unix Programming, Eric Raymond explains that "In a purely orthogonal design, operations do not have side effects; each action (whether it's an API call, a macro invocation, or a language operation) changes just one thing without affecting others. There is one and only one way to change each property of whatever system you are controlling."
So, now look at question (1). C++ supports multiple inheritance, so a class in C++ could inherit from two classes that have the same operation but with two different effects. This has the potential to be non-orthogonal, but C++ requires you to state explicitly which parent class has the feature to be invoked. This will limit the operation to only one effect, so orthogonality is maintained. See Multiple inheritance.
And question (2). Java does not allow multiple inheritance. A class can only derive from one base class. Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. Java classes can implement multiple interfaces but there is only one class doing the implementation, so there should only be one effect when a method is invoked. Even if a class implements two interfaces which both have a method with the same name and signature, it will implement both methods simultaneously, so there should only be one effect. See Java interface.
And finally question (3). The difference is that C++ and Java maintain orthogonality by different mechanisms: C++ by demanding the the parent is explicitly specified, so there will be no ambiguity in the effect; and Java by implementing similar methods simultaneously so there is only one effect.
Irrespective of any number of interfaces/ classes you extend there will be only one implementation inside that class. Lets say your class is X.
Now orthogonality says - one change should affect only one module.
If you change your implementation of one interface in class X - will it affect other modules/classes using your class X ? Answer is no - because the other modules/classes are coding by interface not implementation.
Hence orthogonality is maintained.

How can you be DRY with a programming language that doesn't have Reflection? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Any programming language that does not have a suitable reflection mechanism I find seriously debilitating for rapidly changing problems.
It seems with certain languages its incredible hard or not possible to do:
Convention over Configuration
Automatic Databinding
AOP / Meta programming
with out reflection.
Some example languages that do not have some sort of programmatic reflection are:
C, C++, Haskell, OCaml. I'm sure there are plenty more.
To show you can example of DRY (Don't Repeat Yourself) being violated by most of these languages is when you have to write Unit Tests. You almost always need to register your test cases in these languages outside of where you define the test.
How do programmers of these languages mitigate this problem?
EDIT: Common languages that do have reflection for those that do not know are: C#, Java, Python, Ruby, and my personal favorite F# and Scala.
EDIT: The two common approaches it seems are code instrumentation and code generation. However I have never seen instrumentation for C.
Instead of just voting to close, could some one please comment on why this should be closed and I'll delete the post.
You don't.
But you can keep the repetitions close to each other so when changing something, you see something else has to be changed too.
For example, I wrote a JSON-Parser that outputs objects, a typical call looks like this:
struct SomeStruct
{
int a;
int b;
double c;
typedef int serializable;
template<class SerializerT> void serialize(SerializerT& s)
{
s("a",a)("b",b)("c",c);
}
};
Sure, when you add a field, you have to add another field in the function, but maybe you don't want to serialize that field (something you'd have to handle in languages with reflection, too), and if you delete a field without removing it from the function, the compiler will complain.
I think it's a matter of degree. Reflection is just one very powerful method of avoiding repetition.
Any time you generalize a function from a specific case you are using DRY principle, the more general you make it the more DRY it is. Just because some languages don't get you where you get with reflection doesn't mean there aren't DRY ways of programming with them. They may not be as DRY, but that doesn't mean they don't have their own unique advantages which in total sum may outweigh the advantages of using a language that has reflection. (For example, speed consequences from heavy use of reflection could be a consideration.)
Also, one method of getting something like the DRY benefits of reflection with a language that doesn't support it is by using a good code-generation tool. In that case you modify the code for different cases once, in the code generation template, and the template pushes it out to different instances in code. (I'm not saying whether or not using code generation is a good thing, but with a good "active" generator it is certainly one way of getting something like the DRY benefit of reflection in a language that doesn't have reflection. And the benefits of code generation go beyond this simple benefit. I'm thinking of something like CodeSmith, although there are many others: http://www.codesmithtools.com/ )
Abstractly, do more at runtime, without the benefits of things like compile-time type checking (you have to essentially write your own type-checking routines) and beautiful code. E.g., use a table instead of a class. (But if you did this, why not use a dynamically-typed language instead?) This is often bad. I do not recommend this.
In C++, generic programming techniques allow you to programmatically include members of a class (is that what you want to do?) via inheritance.
One nice example for C++ unit testing is cxxtest:
http://cxxtest.tigris.org/. It uses convention and a python script to generate your C++ test suite by post-processing your C++ with python.
A good way to think about getting around restrictions in languages is Michael Feathers' notion of "seams". A seam is a place where your program can be changed without changing the code. For example, in C the pre-processor and linker provide seams. In C++ polymorphism is another place. In more dynamic languages like where you can change method definitions, or reflect, you get even more flexibility. Without the seams things can be more complicated and sometimes you just don't want to try to hammer a nail with your shoe but rather go with the flow of the tool at hand.

What are the Pros and Cons of having Multiple Inheritance?

What are the pros and cons of having multiple inheritance?
And why don't we have multiple inheritance in C#?
UPDATE
Ok so it is currently avoided because of the issue with clashes resolving which parent method is being called etc. Surely this is a problem for the programmer to resolve. Or maybe this could be resolve simularly as SQL where there is a conflict more information is required i.e. ID might need to become Sales.ID to resolve a conflict in the query.
Here is a good discussion on the pitfalls of multiple inheritance:
Why should I avoid multiple inheritance in C++?
Here is a discussion from the C# team on why they decided not to allow multiple inheritance:
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85562.aspx
http://dotnetjunkies.com/WebLog/unknownreference/archive/2003/09/04/1401.aspx
It's just another tool in the toolbox. Sometimes, it is exactly the right tool. If it is, having to find a workaround because the language actually prohibits it is a pain and leads to good opportunities to screw it up.
Pros and cons can only be found for a concrete case. I guess that it's quite rare to actually fit a problem, but who are the language designers to decide how I am to tackle a specific problem?
I will give a pro here based on a C++ report-writer I've been converting to REALbasic (which has interfaces but only single-inheritance).
Multiple inheritance makes it easier to compose classes from small mixin base classes that implement functionality and have properties to remember state. When done right, you can get a lot of reuse of small code without having to copy-and-paste similar code to implement interfaces.
Fortunately, REALbasic has extends methods which are like the extension methods recently added to C# in C# 3.0. These help a bit with the problem, especially as they can be applied to arrays. I still ended up with some class hierarchies being deeper as a result of folding in what were previously multiply-inherited classes.
The main con is that if two classes have a method with the same name, the new subclass doesn't know which one to call.
In C# you can do a form of multiple inheritance by including instances of each parent object within the child.
class MyClass
{
private class1 : Class1;
private class2: Class2;
public MyClass
{
class1 = new Class1;
class2 = new Class2;
}
// Then, expose whatever functionality you need to from there.
}
When you inherit from something you are asserting that your class is of that (base) type in every way except that you may implement something slightly differently or add something to it, its actually extremely rare that your class is 2 things at once. Usually it just has behavour common to 2 or more things, and a better way to describe that generally is to have your class implement multiple interfaces. (or possibly encapsulation, depending on your circumstances)
It's one of those help-me-to-not-shoot-myself-in-the-foot quirks, much like in Java.
Although it is nice to extend fields and methods from multiple sources (imagine a Modern Mobile Phone, which inherits from MP3 Players, Cameras, Sat-Navs, and the humble Old School Mobile Phone), clashes cannot be resolved by the compiler alone.

Is it a bad practice to have multiple classes in the same file?

I used to have one class for one file. For example car.cs has the class car. But as I program more classes, I would like to add them to the same file. For example car.cs has the class car and the door class, etc.
My question is good for Java, C#, PHP or any other programming language. Should I try not having multiple classes in the same file or is it ok?
I think you should try to keep your code to 1 class per file.
I suggest this because it will be easier to find your class later. Also, it will work better with your source control system (if a file changes, then you know that a particular class has changed).
The only time I think it's correct to use more than one class per file is when you are using internal classes... but internal classes are inside another class, and thus can be left inside the same file. The inner classes roles are strongly related to the outer classes, so placing them in the same file is fine.
In Java, one public class per file is the way the language works. A group of Java files can be collected into a package.
In Python, however, files are "modules", and typically have a number of closely related classes. A Python package is a directory, just like a Java package.
This gives Python an extra level of grouping between class and package.
There is no one right answer that is language-agnostic. It varies with the language.
One class per file is a good rule, but it's appropriate to make some exceptions. For instance, if I'm working in a project where most classes have associated collection types, often I'll keep the class and its collection in the same file, e.g.:
public class Customer { /* whatever */ }
public class CustomerCollection : List<Customer> { /* whatever */ }
The best rule of thumb is to keep one class per file except when that starts to make things harder rather than easier. Since Visual Studio's Find in Files is so effective, you probably won't have to spend much time looking through the file structure anyway.
No I don't think it's an entirely bad practice. What I mean by that is in general it's best to have a separate file per class, but there are definitely good exception cases where it's better to have a bunch of classes in one file. A good example of this is a group of Exception classes, if you have a few dozen of these for a given group does it really make sense to have separate a separate file for each two liner class? I would argue not. In this case having a group of exceptions in one class is much less cumbersome and simple IMHO.
I've found that whenever I try to combine multiple types into a single file, I always end going back and separating them simply because it makes them easier to find. Whenever I combine, there is always ultimately a moment where I'm trying to figure out wtf I defined type x.
So now, my personal rule is that each individual type (except maybe for child classes, by which a mean a class inside a class, not an inherited class) gets its own file.
Since your IDE Provides you with a "Navigate to" functionality and you have some control over namespacing within your classes then the below benefits of having multiple classes within the same file are quite worth it for me.
Parent - Child Classes
In many cases i find it quite helpful to have Inherited classes within their Base Class file.
It's quite easy then to see which properties and methods your child class inherits and the file provides a faster overview of the overall functionality.
Public: Small - Helper - DTO Classes
When you need several plain and small classes for a specific functionality i find it quite redundant to have a file with all the references and includes for just a 4-8 Liner class.....
Code navigation is also easier just scrolling over one file instead of switching between 10 files...Its also easier to refactor when you have to edit just one reference instead of 10.....
Overall breaking the Iron rule of 1 class per file provides some extra freedom to organize your code.
What happens then, really depends on your IDE, Language,Team Communication and Organizing Skills.
But if you want that freedom why sacrifice it for an iron rule?
The rule I always go by is to have one main class in a file with the same name. I may or may not include helper classes in that file depending on how tightly they're coupled with the file's main class. Are the support classes standalone, or are they useful on their own? For example, if a method in a class needs a special comparison for sorting some objects, it doesn't bother me a bit to bundle the comparison functor class into the same file as the method that uses it. I wouldn't expect to use it elsewhere and it doesn't make sense for it to be on its own.
If you are working on a team, keeping classes in separate files make it easier to control the source and reduces chances of conflicts (multiple developers changing the same file at the same time). I think it makes it easier to find the code you are looking for as well.
It can be bad from the perspective of future development and maintainability. It is much easier to remember where the Car class is if you have a Car.cs class. Where would you look for the Widget class if Widget.cs does not exist? Is it a car widget? Is it an engine widget? Oh maybe it's a bagel widget.
The only time I consider file locations is when I have to create new classes. Otherwise I never navigate by file structure. I Use "go to class" or "go to definition".
I know this is somewhat of a training issue; freeing yourself from the physical file structure of projects requires practice. It's very rewarding though ;)
If it feels good to put them in the same file, be my guest. Cant do that with public classes in java though ;)
You should refrain from doing so, unless you have a good reason.
One file with several small related classes can be more readable than several files.
For example, when using 'case classes', to simulate union types, there is a strong relationship between each class.
Using the same file for multiple classes has the advantage of grouping them together visually for the reader.
In your case, a car and a door do not seem related at all, and finding the door class in the car.cs file would be unexpected, so don't.
As a rule of thumb, one class/one file is the way to go. I often keep several interface definitions in one file, though. Several classes in one file? Only if they are very closely related somehow, and very small (< 5 methods and members)
As is true so much of the time in programming, it depends greatly on the situation.
For instance, what is the cohesiveness of the classes in question? Are they tightly coupled? Are they completely orthogonal? Are they related in functionality?
It would not be out of line for a web framework to supply a general purpose widgets.whatever file containing BaseWidget, TextWidget, CharWidget, etc.
A user of the framework would not be out of line in defining a more_widgets file to contain the additional widgets they derive from the framework widgets for their specific domain space.
When the classes are orthogonal, and have nothing to do with each other, the grouping into a single file would indeed be artificial. Assume an application to manage a robotic factory that builds cars. A file called parts containing CarParts and RobotParts would be senseless... there is not likely to be much of a relation between the ordering of spare parts for maintenance and the parts that the factory manufactures. Such a joining would add no information or knowledge about the system you are designing.
Perhaps the best rule of thumb is don't constrain your choices by a rule of thumb. Rules of thumb are created for a first cut analysis, or to constrain the choices of those who are not capable of making good choices. I think most programmers would like to believe they are capable of making good decisions.
The Smalltalk answer is: you should not have files (for programming). They make versioning and navigation painful.
One class per file is simpler to maintain and much more clear for anyone else looking at your code. It is also mandatory, or very restricted in some languages.
In Java for instance, you cannot create multiple top level classes per file, they have to be in separate files where the classname and filename are the same.
(C#) Another exception (to one file per class) I'm thinking of is having List in the same file as MyClass. Where I envisage using this is in reporting. Having an extra file just for the List seems a bit excessive.

Abstraction VS Information Hiding VS Encapsulation

Can you tell me what is the difference between abstraction and information hiding in software development?
I am confused. Abstraction hides detail implementation and
information hiding abstracts whole details of something.
Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there.
Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition):
Abstraction and encapsulation are complementary concepts: abstraction
focuses on the observable behavior of an object... encapsulation
focuses upon the implementation that gives rise to this behavior...
encapsulation is most often achieved through information hiding, which
is the process of hiding all of the secrets of object that do not
contribute to its essential characteristics.
In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally,
Example:
In the .NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding).
rp
The OP updated his question with several citations that he had found, namely in an article by Edward V. Berard titled, "Abstraction, Encapsulation, and Information Hiding". I am re-posting a slightly expanded and reformatted version of the OP's update, since it should be an answer in its own right.
(All citations are taken from the article mentioned above.)
Abstraction:
"One point of confusion regarding abstraction is its use as both process and an entity. Abstraction, as a process, denotes the extracting of the essential details about an item, or a group of items, while ignoring the inessential details. Abstraction, as an entity, denotes a model, a view, or some other focused representation for an actual item."
Information Hiding:
"Its interface or definition was chosen to reveal as little as possible about its inner workings." — [Parnas, 1972b]
"Abstraction can be […] used as a technique for identifying which information should be hidden."
"Confusion can occur when people fail to distinguish between the hiding of information, and a technique (e.g., abstraction) that is used to help identify which information is to be hidden."
Encapsulation:
"It […] refers to building a capsule, in the case a conceptual barrier, around some collection of things." — [Wirfs-Brock et al, 1990]
"As a process, encapsulation means the act of enclosing one or more items within a […] container. Encapsulation, as an entity, refers to a package or an enclosure that holds (contains, encloses) one or more items."
"If encapsulation was 'the same thing as information hiding,' then one might make the argument that 'everything that was encapsulated was also hidden.' This is obviously not true."
Conclusion:
"Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that help us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible."
Abstraction is hiding the implementation details by providing a layer over the basic functionality.
Information Hiding is hiding the data which is being affected by that implementation. Use of private and public comes under this. For example, hiding the variables of the classes.
Encapsulation is just putting all similar data and functions into a group e.g Class in programming; Packet in networking.
Through the use of Classes, we implement all three concepts - Abstraction, Information Hiding and Encapsulation
Please don't complicate simple concepts.
Encapsulation : Wrapping up of data and methods into a single unit is Encapsulation (e.g. Class)
Abstraction : It is an act of representing only the essential things without including background details. (e.g. Interface)
FOR EXAMPLES AND MORE INFO GOTO :
http://thecodekey.com/C_VB_Codes/Encapsulation.aspx
http://thecodekey.com/C_VB_Codes/Abstraction.aspx
Approved definitions here
P.S.: I also remember the definition from a book named C++ by Sumita Arora which we read in 11th class ;)
The meaning of abstraction given by the Oxford English Dictionary (OED) closest to the meaning intended here is 'The act of separating in thought'. A better definition might be 'Representing the essential features of something without including background or inessential detail.'
Information hiding is the principle that users of a software component (such as a class) need to know only the essential details of how to initialize and access the component, and do not need to know the details of the implementation.
Edit: I seems to me that abstraction is the process of deciding which parts of the implementation that should be hidden.
So its not abstraction VERSUS information hiding. It's information hiding VIA abstraction.
Abstraction
Abstraction is an act of representing essentail details without including the background details. A abstract class have only method signatures and implementing class can have its own implementation, in this way the complex details will be hidden from the user. Abstraction focuses on the outside view. In otherwords, Abstraction is sepration of interfaces from the actual implementation.
Encapsulation
Encapsulation explains binding the data members and methods into a single unit. Information hiding is the main purpose of encapsulation. Encapsulation is acheived by using access specifiers like private, public, protected. Class member variables are made private so that they cann't be accessible directly to outside world. Encapsulation focuses on the inner view. In otherwords, Encapsulation is a technique used to protect the information in an object from the other object.
Abstraction is hiding details of implementation as you put it.
You abstract something to a high enough point that you'll only have to do something very simple to perform an action.
Information hiding is hiding implementation details. Programming is hard. You can have a lot of things to deal with and handle. There can be variables you want/need to keep very close track of. Hiding information ensures that no one accidentally breaks something by using a variable or method you exposed publicly.
These 2 concepts are very closely tied together in object-oriented programming.
Abstraction - It is the process of identifying the essential characteristics of an object
without including the irrelevant and tedious details.
Encapsulation - It is the process of enclosing data and functions manipulating this data into a single unit.
Abstraction and Encapsulation are related but complementary concepts.
Abstraction is the process. Encapsulation is the mechanism by which Abstraction is implemented.
Abstraction focuses on the observable behavior of an object. Encapsulation focuses upon the implementation that give rise to this behavior.
Information Hiding - It is the process of hiding the implementation details of an object. It is a result of Encapsulation.
Abstraction : Abstraction is the concept/technique used to identify what should be the external view of an object. Making only the required interface available.
Information Hiding : It is complementary to Abstraction, as through information hiding Abstraction is achieved. Hiding everything else but the external view.
Encapsulation : Is binding of data and related functions into a unit. It facilitates Abstraction and information hiding. Allowing features like member access to be applied on the unit to achieve Abstraction and Information hiding
In very short
Encapsulation:– Information hiding
Abstraction :– Implementation hiding
Abstraction lets you focus on what the object does while Encapsulation means how an object works
Encapsulation: binding the data members and member functions together is called encapsulation. encapsulation is done through class.
abstraction: hiding the implementation details form usage or from view is called abstraction.
ex:
int x;
we don't know how int will internally work. but we know int will work. that is abstraction.
See Joel's post on the Law of Leaky Abstractions
JoelOnsoftware
Basically, abstracting gives you the freedom of thinking of higher level concepts. A non-programming analogy is that most of us do not know where our food comes from, or how it is produced, but the fact that we (usually) don't have to worry about it frees us up to do other things, like programming.
As for information hiding, I agree with jamting.
It's worth noting these terms have standardized, IEEE definitions, which can be searched at https://pascal.computer.org/.
abstraction
view of an object that focuses on the information relevant to a particular purpose and ignores the remainder of the information
process of formulating a view
process of suppressing irrelevant detail to establish a simplified model, or the result of that process
information hiding
software development technique in which each module's interfaces reveal as little as possible about the module's inner workings and other modules are prevented from using information about the module that is not in the module's interface specification
containment of a design or implementation decision in a single module so that the decision is hidden from other modules
encapsulation
software development technique that consists of isolating a system function or a set of data and operations on those data within a module and providing precise specifications for the module
concept that access to the names, meanings, and values of the responsibilities of a class is entirely separated from access to their realization
idea that a module has an outside that is distinct from its inside, that it has an external interface and an internal implementation
Abstraction allows you to treat a complex process as a simple process. For example, the standard "file" abstraction treats files as a contiguous array of bytes. The user/developer does not even have to think about issues of clusters and fragmentation. (Abstraction normally appears as classes or subroutines.)
Information hiding is about protecting your abstractions from malicious/incompetent users. By restricting control of some state (hard drive allocations, for example) to the original developer, huge amounts of error handling becomes redundant. If nobody else besides the file system driver can write to the hard drive, then the file system driver knows exactly what has been written to the hard drive and where. (The usual manifestation of this concept is private and protected keywords in OO languages.)
To abstract something we need to hide the detail or to hide the detail of something we need to abstract it.
But, both of them can be achieved by encapsulation.
So, information hiding is a goal, abstraction is a process, and encapsulation is a technique.
Abstraction simply means the technique in which only essential details of software is made visible to the user to help the user to use or operate with software, thus implementation details of that software are not shown(are made invisible).
Encapsulation is the technique that have package that hold one or more items and hence some of information (particularly program details) became visible and some not visible to the user, so encapsulation is achieved through information hiding.
In summary. Abstraction is for observable behavior (externally) and encapsulation is for invisibility (internally) but these two are really complementary.
Just adding on more details around InformationHiding, found This link is really good source with examples
InformationHiding is the idea that a design decision should be hidden from the rest of the system to prevent unintended coupling. InformationHiding is a design principle. InformationHiding should inform the way you encapsulate things, but of course it doesn't have to.
Encapsulation is a programming language feature.
Both Abstraction and Encapsulation are two of the four basic OOP concepts which allow you to model real-world things into objects so that you can implement them in your program and code. Many beginners get confused between Abstraction and Encapsulation because they both look very similar. If you ask someone what is Abstraction, he will tell that it's an OOP concept which focuses on relevant information by hiding unnecessary detail, and when you ask about Encapsulation, many will tell that it's another OOP concept which hides data from outside world. The definitions are not wrong as both Abstraction and Encapsulation does hide something, but the key difference is on intent.
Abstraction hides complexity by giving you a more abstract picture, a sort of 10,000 feet view, while Encapsulation hides internal working so that you can change it later. In other words, Abstraction hides details at the design level, while Encapsulation hides details at the implementation level.
After reading all the above answers one by one I cant stop myself from posting that
abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system.
Encapsulation is quite clear from above however ->
The term encapsulation refers to the hiding of state details, but extending the concept of data type from earlier programming languages to associate behavior most strongly with the data, and standardizing the way that different data types interact, is the beginning of abstraction.
reference wiki
I too was very confused about the two concepts of Abstraction and Encapsulation. But when I saw the abstraction article on myjavatrainer.com, It became clear to me that Abstraction and Encapsulation are Apples and Oranges, you can't really compare them because both are required.
Encapsulation is how the object is created, and abstraction is how the object is viewed in the outside world.
Encapsulation: binding data and the methods that act on it. this allows the hiding of data from all other methods in other classes.
example: MyList class that can add an item, remove an item, and remove all items
the methods add, remove, and removeAll act on the list(a private array) that can not be accessed directly from the outside.
Abstraction: is hiding the non relevant behavior and data.
How the items are actually stored, added, or deleted is hidden (abstracted).
My data may be held in simple array, ArrayList, LinkedList, and so on.
Also, how the methods are implemented is hidden from the outside.
Encapsulation- enforcing access to the internal data in a controlled manner or preventing members from being accessed directly.
Abstraction- Hiding the implementation details of certain methods is known as abstraction
Let's understand with the help of an example:-
class Rectangle
{
private int length;
private int breadth;// see the word private that means they cant be accesed from
outside world.
//now to make them accessed indirectly define getters and setters methods
void setLength(int length)
{
// we are adding this condition to prevent users to make any irrelevent changes
that is why we have made length private so that they should be set according to
certain restrictions
if(length!=0)
{
this.length=length
}
void getLength()
{
return length;
}
// same do for breadth
}
now for abstraction define a method that can only be accessed and user doesnt know
what is the body of the method and how it is working
Let's consider the above example, we can define a method area which calculates the area of the rectangle.
public int area()
{
return length*breadth;
}
Now, whenever a user uses the above method he will just get the area not the way how it is calculated. We can consider an example of println() method we just know that it is used for printing and we don't know how it prints the data.
I have written a blog in detail you can see the below link for more info
abstraction vs encapsulation

Resources