Description of what an interface does? [duplicate] - oop

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

Related

OOP Principle Differences between Interfaces and Abstract Classes

I understand that Abstract Classes are classes that contain declared methods that do not all necessarily have a specified implementation because the code would have to be declared in the child class instead but Im finding it difficult to understand the OOP concept behind the introduction of Interfaces.
What are the architectural and principle differences between interfaces and abstract classes if the abstract class has no defined methods and states (Aside from the fact that abstract classes can have constructors)?
In addition, why should anyone use abstract classes and interfaces in the first place? I understand that it adds restrictions to your code not allowing people to defined subclasses without specified methods but the code would work in the exact same way if the non implemented declared methods were not present in the interface and abstract class. So what is the implied benefit of writing methods with no implementation only to implement it later in the subclass?
I have seen many posts on Interface vs Abstract Classes but im interested in the principle differences between the two, not their functional differences.
Coming back to my own question after a year, I have discovered the answer that I wanted.
A class, regardless of being abstract or not, always tries to define/design what entities look like from their behaviour to their states. In the case of an abstract class, we are modelling an idea/entity that we do not want to be instantiated during run time. Example, if we had an app about dogs and cats, we may want to define what an animal is and then extend this idea to define what a dog/cat is by extending our base animal class. An animal object will never be instantiated but a dog/cat will.
An interface on the other hand are a set of methods that represents some form of interactions to be expected from any class. As long as a class implements an interface, you know what methods to expect from it. Thus, you can have two entities (classes) that do not relate to one another that implement the same interface. Example, a dog and person class may both implement a 'digest' interface. This means that they are all able to digest food as we have explicitly stated what functions to expect in the interface to enable food digestion behaviour. Obviously the details of the implementation differs thus the functions defined in the interface are outlined in the classes implementing them.

Difference between abstract class and interface in Objective-C

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.

What is the difference between subtyping and inheritance in OO programming?

I could not find the main difference. And I am very confused when we could use inheritance and when we can use subtyping. I found some definitions but they are not very clear.
What is the difference between subtyping and inheritance in object-oriented programming?
In addition to the answers already given, here's a link to an article I think is relevant.
Excerpts:
In the object-oriented framework, inheritance is usually presented as a feature that goes hand in hand with subtyping when one organizes abstract datatypes in a hierarchy of classes. However, the two are orthogonal ideas.
Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be invoked on an object of type A can also be invoked on an object of type B.
Inheritance refers to reuse of implementations. A type B inherits from another type A if some functions for B are written in terms of functions of A.
However, subtyping and inheritance need not go hand in hand. Consider the data structure deque, a double-ended queue. A deque supports insertion and deletion at both ends, so it has four functions insert-front, delete-front, insert-rear and delete-rear. If we use just insert-rear and delete-front we get a normal queue. On the other hand, if we use just insert-front and delete-front, we get a stack. In other words, we can implement queues and stacks in terms of deques, so as datatypes, Stack and Queue inherit from Deque. On the other hand, neither Stack nor Queue are subtypes of Deque since they do not support all the functions provided by Deque. In fact, in this case, Deque is a subtype of both Stack and Queue!
I think that Java, C++, C# and their ilk have contributed to the confusion, as already noted, by the fact that they consolidate both ideas into a single class hierarchy. However, I think the example given above does justice to the ideas in a rather language-agnostic way. I'm sure others can give more examples.
A relative unfortunately died and left you his bookstore.
You can now read all the books there, sell them, you can look at his accounts, his customer list, etc. This is inheritance - you have everything the relative had. Inheritance is a form of code reuse.
You can also re-open the book store yourself, taking on all of the relative's roles and responsibilities, even though you add some changes of your own - this is subtyping - you are now a bookstore owner, just like your relative used to be.
Subtyping is a key component of OOP - you have an object of one type but which fulfills the interface of another type, so it can be used anywhere the other object could have been used.
In the languages you listed in your question - C++, Java and C# - the two are (almost) always used together, and thus the only way to inherit from something is to subtype it and vice versa. But other languages don't necessarily fuse the two concepts.
Inheritance is about gaining attributes (and/or functionality) of super types. For example:
class Base {
//interface with included definitions
}
class Derived inherits Base {
//Add some additional functionality.
//Reuse Base without having to explicitly forward
//the functions in Base
}
Here, a Derived cannot be used where a Base is expected, but is able to act similarly to a Base, while adding behaviour or changing some aspect of Bases behaviour. Typically, Base would be a small helper class that provides both an interface and an implementation for some commonly desired functionality.
Subtype-polymorphism is about implementing an interface, and so being able to substitute different implementations of that interface at run-time:
class Interface {
//some abstract interface, no definitions included
}
class Implementation implements Interface {
//provide all the operations
//required by the interface
}
Here, an Implementation can be used wherever an Interface is required, and different implementations can be substituted at run-time. The purpose is to allow code that uses Interface to be more widely useful.
Your confusion is justified. Java, C#, and C++ all conflate these two ideas into a single class hierarchy. However, the two concepts are not identical, and there do exist languages which separate the two.
If you inherit privately in C++, you get inheritance without subtyping. That is, given:
class Derived : Base // note the missing public before Base
You cannot write:
Base * p = new Derived(); // type error
Because Derived is not a subtype of Base. You merely inherited the implementation, not the type.
Subtyping doesn't have to be implemented via inheritance. Some subtyping that is not inheritance:
Ocaml's variant
Rust's lifetime anotation
Clean's uniqueness types
Go's interface
in a simple word: subtyping and inheritance both are polymorphism, (inheritance is a dynamic polymorphism - overriding). Actually, inheritance is subclassing, it means in inheritance there is no warranty to ensure capability of the subclass with the superclass (make sure subclass do not discard superclass behavior), but subtyping(such as implementing an interface and ... ), ensure the class does not discard the expected behavior.

Why is the key idea behind OOP polymorphism?

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 ;)

What's the difference between an interface and an abstract class? [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate:
When to use an interface instead of an abstract class and vice versa?
Probably one of the most famous software developer job interview questions.
What would be your answer?
EDIT: I'm trying to find out how you would answer this in a real-life situation. Please try to formulate your answer as you would on a real job interview (be complete, but don't be too long, post no links of course).
An interface only describes the actual signature of its methods etc. Any class implementing that interface must then provide an explicit implementation.
An abstract class can contain a partial implementation of its methods etc.
An abstract class can have member variables, an interface cannot (or, in C++, should not).
In Java, an "Interface" is a well-defined syntactical element, while in C++ it's merely a design pattern.
Interfaces provide definitions of methods that must be implemented by a class. The purpose of interfaces is to allow you to generalise specific functionality regardless of implementation. You may have an IDatabase interface that has an Open/Close method. The class that implements that interface may be connecting to a MySQL database or MS Access database. Irrespective of how it accomplishes this task, the goal is still the same...Open database, close database.
Abstract classes are base classes that contain some abstract methods. They cannot be instantiated they are to be derived from. The purpose of an Abstract class is to allow you to define some generic functionality and sub-class to implement more specific functionality where appropriate.
So in summary, you should use interfaces when the implementation of each class differs completely. Use abstract classes when you have some similar behaviour but need to implement parts differently.
Hope that helps.
I would say that the difference is language dependent, but that in C++ at least, abstract classes are the means by which interfaces are implemented.
As far as job interviews are concerned, I've always heard that the key point is that an interface is a contract; an interface, while not implementing it itself, guarantees functionality.