In the book C++ Primer, the author wrote: "The key idea behind OOP is polymorphism". I am not sure I understand what the author meant. What about other important stuff: Abstract, Inheritance, etc.
Can anyone elaborate on that, please?
Edit:
I do not ask "What is polymorphism". I am asking "Why polymorphism is the key behind OOP"? Why not inheritance is the key?
I'm not sure that it's the key to OOP. That's just someone's opinion.
I think there are four keys: abstract data types, encapsulation, inheritance, and polymorphism. They belong together.
Each idea depends on the previous ones. ADT is the only one that stands on its own. Encapsulation needs ADT. Polymorphism requires inheritance.
Polymorphism helps to eliminate if, switch, and case statements. You don't have to write code to figure out what to do based on object type; the virtual table simply calls the right method for you behind the scenes.
The Author may be saying this because :
When class B inherits from A then class B can be typecasted to A ----> Which is also called as polymorohism. So Inheritance directly allows polymorphism.
When A implements interface I*something* then A can rome around as I*something* which is also called as polymorphism. So Interfaces makes polymorphism come true.
Abstract : Abstract class is just another class which cannt be instantiated and act as base class (generally). Non abstract Child classes can be type casted to Abstract class and hence polymorphism.
So infact its seen that most concept of OOP can be seen as polymorphism and due to this Author might have said that.
Generally it's the idea of creating objects (with their fields, methods, etc) which can have more than one form - derived (abstract) classes, implemented interfaces and so on.
And you would have had your answer in few seconds only, if you would've had asked google, wikipedia and so on, first ;)
Related
Recently I was talking to a very experienced programmer (8+ years of experience) and he told me that "combining data with functions that work with them in a capsula" is a wrong term for encapsulation. He told me that that was what encapsulation allowed me to do, but not what encapsulation itself was. He told me that as soon as inheritance is not possible without encapsulation, encapsulation must be just a capsula creation (class or anything like that). But today I got interviewed by a less experienced programmer and he was so sure all those classic definitions on wikipedia were right he told me not to even think of passing the interview. So I tried to google all that stuff about encapsulation, and about inheritence not being possible without encapsulation, but didn't find anything. But I can't believe that experienced programmer was wrong, he convienced not only me, but other experienced programmers too. Maybe that correct definition is just something that is lost in the chunks of useless and unimportant info?
So please, give me answers on these two questions:
1) can inheritence be possible without encapsulation? (A class's Inheritence from a class)
2) If not, then can we consider declaring a class encapsulation? Because only after declaring a class we can inherit.
Well, I'm Sorry, but I fail to see the connection between encapsulation and inheritance.
Encapsulation is hiding your internal implementation behind a publicly visible API.
Basically, it's a separation between a type's actual implementation and what it exposes.
In a broad sense, one can look at even the human body and see encapsulation:
For example: You are breathing air in and out, that's your public API, but the internals of what your body is doing with this air are hidden away inside your respiratory system - your lunges passes oxygen to your blood and collects from it carbon dioxide in return - thus changing the mixture ratio of the gasses in the air you breath, but none of this is visible to the outside world.
Inheritance, in the OOP world, is the ability to take a specific object, and derive an even more specific object from it, while adding capabilities (and sometimes mutating existing capabilities via overriding).
For example: A Dog is a kind of Mammal which is a kind of Animal.
An Animal might contain methods such as Eat() and properties such as Weight and Age.
A Mammal might override the Eat() method to implement suckling (from it's mother's breast) as an infant, but depending on it's age eating solid foods.
A Dog might introduce another capability such as Bark.
All of this have nothing to do with encapsulation as desribed in the previous paragraph.
Inheritance is tightly related to another core principle of object oriented programming called Polymorphism - basically, the ability to reference a derived class using it's base class type - perhaps you (or the interviewer) are confusing the two?
However, today is the first time I've seen another definition of encapsulation (and I've been working with oop languages for about two decades now):
A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
Under that
definition, encapsulation is the process of creating capsules - stand-alone code snippets that holds data and ways to interact with it - a.k.a types, classes, etc', and is somewhat related to inheritance - in order to inherit a type, that type first needs to be defined.
However, the way I see it, this definition is not enough to define encapsulation. It can be a part of the definition, but not a stand-alone definition of encapsulation.
One of the most frequently asked questions on iOS developer interview is - difference between abstract classed and interface.
I don't know an answer and i don't get it neither. Interface is a section of class, when you declared methods. it could be open for other classes (public, .h file) or hidden in implementation.
Abstract class is a class, that is only used to create hidden subclasses and it should not have own init methods (if i understand correct).
So, what exactly is answer for that question? And what does that question mean?
I did spend time searching for an answers, but answers wasn't related to Obj-C, so i can't figure out by myself.
I hope someone could provide clear answer and that question would be helpful for those guys, who want to pass an interview.
A good way to approach this problem is first think about it in general programming theory, and then in more concrete Objective-C context.
Abstract Class - is a class intended purely for subclassing, one must not instantiate it. Abstract class declares something and has also the implementation for that.
What is the reason for having such special class? It is modelled after real life! :)
Imagine an abstraction - an animal. What has each animal in common? They are all alive (and can die). They need to eat. The can move in space. These traits are common and fundamental to all animals. I heaven't heard about an animal that doesn't needs food, cannot move and lives forever. Other then that there is a LOT of not so fundamental differences between various animals.
There is no animal on the planet which is purely an abstract animal like that. That set of fundamental behaviours, traits is simply not enough to be a concrete animal..
There is an implied principle, that to be a concrete animal, you have to have some additional traits besides those fundamental ones.
Now, in programming, we need to be able to somehow
express these fundamentals (interface declaration)
have a way of describing how they work (implementation)
attribute them to a class
prevent instantiation
ensure that any concrete animal will have them (inheritance)
We know, what these fundamentals are (declared public interface) and we know in practice how they manifest themselves concretely (implementation of those declared traits). We want them to be inherited by all concrete entities. So we do it in the abstract class because it satisfies these condition I mentioned. It contains all the fundamentals, has their implementation, but cannot be instantiated on its own.
Abstract class is an abstraction over a set of related entities that captures what is fundamentally common between all of them., tells us how it is done..and ensures all more concrete entities will inherit this.
Interface - is something less. Let's a have a real life analogy. Person, robot, animal, wind (a force of nature).
Some people can sing. A robot has a voice synthesizer module embedded so it can sing. The autumn wind touching my teracce glass "sings" a lot I can tell you. And Tinka (r.i.p) my dog, was actually a good singer too.
But really, "singing" between these four has the only thing in common - you can hear it as pleasing sound in your ears. How the singing happens for those four, differs a lot in reality. (implementation)
Another complication is, certainly not all people, dogs, winds, or animals can sing. Some of them can.
So how would we reflect this situation in programming? Via interface :)
You can have an interface called "SingInterface" which in our case has one behaviour/trait/functionality declared and it is sing. Interface simply declares something and that's it. Interface doesn't say how that something is done, there is no concrete implementation. Nor does it say who can do it, the trait in the interface is not limited to one type or one class really. (see http://www.nasa.gov/centers/goddard/universe/black_hole_sound.html)
Interface is a list of 1 to N traits/functionalities without knowing how concretely will they be realized, and that list of traits/functionalities that can be arbitrarily (no rules exist to who) attributable to entities from disparate sets that are fundamentally different (animals or robots).
Object oriented programming borrows many concepts from real life. That's why these analogies work so well.
In Objective C, contrary to some other languages (C# etc),
there is no language level support for abstract classes. It is not possible to enforce that a class is abstract during compilation. A class is abstract only by convention and respecting that convention by developers.
As for interfaces, a word "protocol" is used in objective C. It's just a different word for the same thing.
In objective C you can
code against the interface ..by declaring some object as
id<protocolName>
add additional functionality to classes by declaring that they conform to protocol which you do in the class interface
#interface ClassName <protocolName>
So, there might possibly be even a case where your class is a subclass of abstract class, and it also conform to some protocol.
Thanks to Rob Napier's comment at here. My answer is:
An interface is just the outside view of a class. What it reveals publicly.
In Swift you just write a class in a single .Swift file, and if ask Xcode to show you can generate its interface. Xcode will only then show properties/functions that are public/internal.
In Objective-C. You first have to manually write the interface...declaring what of the class is public and then manually write the implementation. An interface without implementation is not compilable. It's like you saying this is how my class will look like, but then you have provided nothing for how it implements the public methods or how you manipulate your properties—when you must (provide).
Abstract relieves you of how it implements
For abstract classes, you shouldn't provide any implementation, only that it would have such parameters or it would have such functions with such signatures. However an abstract class is compilable on its own. Because you don't need to provide anything more than that.
I've searched in here and other forums and couldn't find a good answer..
I kind of know that Extending classes isn't the best of practices. And that I should use Interfaces more. my problem is that usually I start creating Interfaces and then move to Abstract classes because there's always some functionality that I want implemented on a super class so that I don't have to replicate it in every child classes.
For instance, I have a Vehicle class and the Car and Bike child classes. a lot of functionality could be implemented on the Vehicle class, such as Move() and Stop(), so what would be the best practice to keep the architecture clean, avoid code repetition and use Interfaces instead of Inheritance?
Thanks a lot!
(if you have no idea why I'm asking this you may read this interesting article: http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html)
Inheritance ('extending classes') imposes significant limitations on class design and I'm not sure the use of interfaces as a replacement for inheritance is the best idea since it fails the DRY test.
These days, Composition is favored over Inheritance, so you might consider this post: Prefer composition over inheritance?
Interesting question. Everyone has different approaches. But it all based on personal experience and choice.
Usually, i start with an interface, then let an abstract class inherit that interface. And implement common actions there, and let others to be implemented by who ever inherits this class.
This give few advantageous based on by experience,
1.During function calls you can pass the elements as interface type or abstract class type.
2.Common variables such as ID, Names etc can be put on abstract class.
3.Easy for maintenance. For example, if you want to implement a new interface, then just implement in the abstract quickly.
If you keep in mind fundamental difference between interfaces and classes it will make it easier to decide which one to use. The difference is that interfaces represent just a protocol (usually behavioral) between objects involved, while abstract classes represent some unfinished constructions that involve some parts (data). In car example, interface is essentially a blueprint for the generic car. And abstract class would be like prefabricated specific model car body that needs to be filled with remaining parts to get final product. Interfaces don't even have to be in Java - it will not change anything - still blueprint.
Typically you would use abstract class within your specific implementation framework to provide its consumers with some basic functionality. If you just state that you never use abstract class in favor of interface - it's plain wrong from practical standpoint. What if you need 10 implementations of the same interface with 90% of the same code. Replicate code 10 times? Ok, may be you would use abstract class here but put interface on top of it. But why would you do that if you never intend to offer your class hierarchy to external consumers?
I am using word external in very wide sense - it can be just different package in your project or remote consumer.
Ultimately, many of those things are preferences and personal experiences, but I disagree with most blanket statements like extends is evil. I also prefer not to use extra classes (interfaces or abstract) unless it is required by specific parts of the design.
Just my two cents.
Inheritance allows code reuse and substitutability, but restricts polymorphism. Composition allows code reuse but not substitutability. Interfaces allow substitutability but not code reuse.
The decision of whether to use inheritance, composition, or interfaces, boils down to a few simple principles:
If one needs both code reuse and substitutability, and the restrictions imposed on polymorphism aren't too bad, use inheritance.
If one needs code reuse, but not substitutability, use composition.
If one needs substitutability, but not code reuse, or if the restrictions inheritance would impose upon polymorphism would be worse than duplicated code, use interfaces.
If one needs substitutability and code reuse, but the restrictions imposed by polymorphism would be unacceptable, use interfaces to wrap encapsulated objects.
If one needs substitutability and code reuse, and the restrictions imposed by polymorphism would not pose any immediate problem but might be problematic for future substitutable classes, derive a model base class which implements an interface, and have those classes that can derive from it do so. Avoid using variables and parameters of the class type, though--use the interface instead. If you do that, and there is a need for a substitutable class which cannot very well derive from the model base class, the new class can implement the interface without having to inherit from the base; if desired, it may implement the interface by wrapping an encapsulated instance of a derivative of the model type.
Judgment may be required in deciding whether future substitutable classes may have difficulty deriving from a base class. I tend to think approach #5 often offers the best of all worlds, though, when substitutability is required. It's often cheaper than using interfaces alone, and not much more expensive than using inheritance alone. If there is a need for future classes which are substitutable but cannot be derived from the base, it may be necessary to convert the code to use approach #5. Using approach #5 from the get-go would avoid having to refactor the code later. (Of course, if it's never necessary to substitute a class that can't derive from the base, the extra cost--slight as it may be--may end up being unnecessary).
Agree with tofutim - in your current example, move and stop on Vehicle is reasonable.
Having read the article - I think it's using powerful language to push a point... remember - inheritance is a tool to help get a job done.
But if we go with the assumption that for whatever reasons you can't / won't use the tool in this case, you can start by breaking it down into small interfaces with helper objects and/or visitors...
For example -
Vehicle types include submarine, boat, plane, car and bike. You could break it down into interfaces...
IMoveable
+ Forward()
+ Backward()
+ Left()
+ Right()
IFloatable
+ Dock()
ISink()
+ BlowAir()
IFly()
+ Takeoff()
+ Land()
And then your classes can aggregate the plethora of interfaces you've just defined.
The problem is though that you may end up duplicating some code in the car / bike class for IMoveable.Left() and IMoveable.Right(). You could factor this into a helper method and aggregate the helper... but if you follow it to its logical conclusion, you would still end up refactoring many things back into base classes.
Inheritance and Aggregation are tools... neither of which are "evil".
Hope that helps.
Do you want an answer for your specific case, or in general? In the case you described, there is nothing wrong with using an Abstract class. It doesn't make sense use an interface when all of the clients would need to implement the exact same code for Move() and Stop().
Don't believe all you read
Many times, inheritance is not bad, in fact, for data-hiding, it may be a good idea.
Basically, only use the policy of "interfaces only" when you're making a very small tree of classes, otherwise, I promise it will be a pain. Suppose you have a Person "class" (has eat() and sleep), and there are two subclasses, Mathematician (has doProblem() ) and Engineer ( buildSomething() ), then go with interfaces. If you need something like a Car class and then 56 bazillion types of cars, then go with inheritance.
IMHO.
I think, that Interfaces sometime also evil. They could be as avoidance of multiple inheritance.
But if we compare interface with abstract class, then abstract class is always more than interface. Interface is always some aspect of the class -- some viewpoint, and not whole as a class.
So I don't think you should avoid inheritance and use iterfaces everywhere -- there should be balance.
This is more of a subjective question, so I'm going to preemptively mark it as community wiki.
Basically, I've found that in most of my code, there are many classes, many of which use each other, but few of which are directly related to each other. I look back at my college days, and think of the traditional class Cat : Animal type examples, where you have huge inheritance trees, but I see none of this in my code. My class diagrams look like giant spiderwebs, not like nice pretty trees.
I feel I've done a good job of separating information logically, and recently I've done a good job of isolating dependencies between classes via DI/IoC techniques, but I'm worried I might be missing something. I do tend to clump behavior in interfaces, but I simply don't subclass.
I can easily understand subclassing in terms of the traditional examples such as class Dog : Animal or class Employee : Person, but I simply don't have anything that obvious I'm dealing with. And things are rarely as clear-cut as class Label : Control. But when it comes to actually modeling real entities in my code as a hierarchy, I have no clue where to begin.
So, I guess my questions boil down to this:
Is it ok to simply not subclass or inherit? Should I be concerned at all?
What are some strategies you have to determine objects that could benefit from inheritance?
Is it acceptable to always inherit based on behavior (interfaces) rather than the actual type?
Inheritance should always represent an "is-a" relationship. You should be able to say "A is a B" if A derives from B. If not, prefer composition. It's perfectly fine to not subclass when it is not necessary.
For example, saying that FileOpenDialog "is-a" Window makes sense, but saying that an Engine "is-a" Car is nonsense. In that case, an instance of Engine inside a Car instance is more appropriate (It can be said that Car "is-implemented-in-terms-of" Engine).
For a good discussion of inheritance, see Part 1 and Part 2 of "Uses and Abuses of Inheritance" on gotw.ca.
As long as you do not miss the clear cut 'is a' relationships, it's ok and in fact, it's best not to inherit, but to use composition.
is-a is the litmus test. if (Is X a Y?) then class X : Y { } else class X { Y myY; } or class Y { X myX; }
Using interfaces, that is, inheriting behavior, is a very neat way to structure the code via adding only the needed behavior and no other. The tricky part is defining those interfaces well.
No technology or pattern should be used for its own sake. You obviously work in a domain where classes tend to not benefit from inheritance, so you shouldn't use inheritance.
You've used DI to keep things neat and clean. You separated the concerns of your classes. Those are all good things. Don't try and force inheritance if you don't really need it.
An interesting follow-up to this question would be: Which programming domains do tend to make good use of inheritance? (UI and db frameworks have already been mentioned and are great examples. Any others?)
I also hate the Dog -> Mammal -> Animal examples, precisely because they do not occur in real life.
I use very little subclassing, because it tightly couples the subclass to the superclass and makes your code really hard to read. Sometimes implementation inheritance is useful (e.g. PostgreSQLDatabaseImpl and MySQLDatabaseImpl extend AbstractSQLDatabase), but most of the time it just makes a mess of things. Most of the time I see subclasses the concept has been misused and either interfaces or a property should be used.
Interfaces, however, are great and you should use those.
Generally, favour composition over inheritance. Inheritance tends to break encapsulation. e.g. If a class depends on a method of a super class and the super class changes the implementation of that method in some release, the subclass may break.
At times when you are designing a framework, you will have to design classes to be inherited. If you want to use inheritance, you will have to document and design for it carefully. e.g. Not calling any instance methods (that could be overridden by your subclasses) in the constructor. Also if its a genuine 'is-a' relationship, inheritance is useful but is more robust if used within a package.
See Effective Java (Item 14, and 15). It gives a great argument for why you should favour composition over inheritance. It talks about inheritance and encapsulation in general (with java examples). So its a good resource even if you are not using java.
So to answer your 3 questions:
Is it ok to simply not subclass or inherit? Should I be concerned at all?
Ans: Ask yourself the question is it a truly "is-a" relationship? Is decoration possible? Go for decoration
// A collection decorator that is-a collection with
public class MyCustomCollection implements java.util.Collection {
private Collection delegate;
// decorate methods with custom code
}
What are some strategies you have to determine objects that could benefit from inheritance?
Ans: Usually when you are writing a framework, you may want to provide certain interfaces and "base" classes specifically designed for inheritance.
Is it acceptable to always inherit based on behavior (interfaces) rather than the actual type?
Ans: Mostly yes, but you'd be better off if the super class is designed for inheritance and/or under your control. Or else go for composition.
IMHO, you should never do #3, unless you're building an abstract base class specifically for that purpose, and its name makes it clear what its purpose is:
class DataProviderBase {...}
class SqlDataProvider : DataProviderBase {...}
class DB2DataProvider : DataProviderBase {...}
class AccountDataProvider : SqlDataProvider {...}
class OrderDataProvider : SqlDataProvider {...}
class ShippingDataProvider : DB2DataProvider {...}
etc.
Also following this type of model, sometimes if you provide an interface (IDataProvider) it's good to also provide a base class (DataProviderBase) that future consumers can use to conveniently access logic that's common to all/most DataProviders in your application model.
As a general rule, though, I only use inheritance if I have a true "is-a" relationship, or if it will improve the overall design for me to create an "is-a" relationship (provider model, for instance.)
Where you have shared functionality, programming to the interface is more important than inheritance.
Essentially, inheritance is more about relating objects together.
Most of the time we are concerned with what an object can DO, as opposed to what it is.
class Product
class Article
class NewsItem
Are the NewsItem and Article both Content items? Perhaps, and you may find it useful to be able to have a list of content which contains both Article items and NewsItem items.
However, it's probably more likely you'll have them implement similar interfaces. For example, IRssFeedable could be an interface that they both implement. In fact, Product could also implement this interface.
Then they can all be thrown to an RSS Feed easily to provide lists of things on your web page. This is a great example when the interface is important whereas the inheritance model is perhaps less useful.
Inheritance is all about identifying the nature of Objects
Interfaces are all about identifying what Objects can DO.
My class hierarchies tend to be fairly flat as well, with interfaces and composition providing the necessary coupling. Inheritance seems to pop up mostly when I'm storing collections of things, where the different kinds of things will have data/properties in common. Inheritance often feels more natural to me when there is common data, whereas interfaces are a very natural way to express common behavior.
The answer to each of your 3 questions is "it depends". Ultimately it will all depend on your domain and what your program does with it. A lot of times, I find the design patterns I choose to use actually help with finding points where inheritance works well.
For example, consider a 'transformer' used to massage data into a desired form. If you get 3 data sources as CSV files, and want to put them into three different object models (and maybe persist them into a database), you could create a 'csv transformer' base and then override some methods when you inherit from it in order to handle the different specific objects.
'Casting' the development process into the pattern language will help you find objects/methods that behave similarly and help in reducing redundant code (maybe through inheritance, maybe through the use of shared libraries - whichever suits the situation best).
Also, if you keep your layers separate (business, data, presentation, etc.), your class diagram will be simpler, and you could then 'visualize' those objects that aught to be inherited.
I wouldn't get too worried about how your class diagram looks, things are rarely like the classroom...
Rather ask yourself two questions:
Does your code work?
Is it extremely time consuming to maintain? Does a change sometimes require changing the 'same' code in many places?
If the answer to (2) is yes, you might want to look at how you have structured your code to see if there is a more sensible fashion, but always bearing in mind that at the end of the day, you need to be able to answer yes to question (1)... Pretty code that doesn't work is of no use to anybody, and hard to explain to the management.
IMHO, the primary reason to use inheritance is to allow code which was written to operate upon a base-class object to operate upon a derived-class object instead.
This question already has answers here:
Why can't I seem to grasp interfaces?
(26 answers)
Closed 3 years ago.
With regards to OOP, how would you describe an interface?
What I mean is, sub-classing can be described as "Has-A", and inheritance could be "Is-A". A member method could be "Can-Do".
Is there any way this could be extended (no pun intended) to describe what an interface does?
I think of objects as nouns, methods as verbs, and interfaces as adjectives (of course this analogy is oversimplified, but frequently works well enough).
Example: an interface Serializable works like an adjective, in that it applies some qualities to an object that implement that interface, but does not change what that object is. We can say, "this is a serializable object." But we don't say, "this object is a serializable," nor do we say, "this object has a serializable."
I also like Federico's answer that an interface is "CAN-DO".
An interface is a group of related operations that the class supports. Together, the methods in an interface describe what the class can do.
Just like a noun can take multiple adjectives, a class can implement multiple interfaces, as long as they don't conflict. The union of all the interfaces a class implements is the sum of what the class can do.
In practical terms, an interface is a set of method signatures, without the code implementing those methods. Just the method name and arguments. Depending on the language, a method signature may also include return type, and exceptions thrown.
An interface consists of methods, but not data members.
BTW, I wouldn't say sub-classing is HAS-A. My understanding is that sub-classing is the same as inheritance, so these are both IS-A. Whereas HAS-A is called Aggregation or Composition.
Composition is where an object owns another object. Destroying the outer object also destroys the inner objects. Example: University composes Departments. Close the University, and the Departments disappear.
Aggregation is where an object includes another object, but does not own it. Destroying the outer object does not destroy the inner objects. Example: University employs Professors, but closing the University does not kill the Professors.
An interface is an abstract base class with all pure virtual members.
So looking at your Has-A/Is-A, it should be similar to whatever you would be apply for an abstract base class.
Interfaces generally exist in languages that do not fully support multiple inheritance as a way to more safely offer some of the same benefits.
Acts-As-A.
As is your description for methods, I would also describe an interface as a "Can-Do". An interface is a contract like "all the classes that implement me, can do these things".
Joel that isn't exaclty what an interface is. It is like a abstract base class in a way but it has no implementation of the methods and properties.
This pretty much sums up what an interface is.
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_interrfaces03052006095933AM/csharp_interrfaces.aspx?ArticleID=cd6a6952-530a-4250-a6d7-54717ef3b345