tags:

views:

340

answers:

4

Hi All, I was giving a test and got one question. QUESTION: What do you use if you want to ensure that all methods and properties are implemented? a)Inheritance. b)Polymorphism. c)Encapsulation d)Interface.

I think its Interface. Am I right or the. ans is diff?

+8  A: 

Yep, use an interface. An interface is basically a contract saying "hey, you need to implement these members, or I'm not going to compile."

Tim S. Van Haren
Thanks...glad to know I was rite :-)
Wondering
A: 

Actually, these concepts don't even compare to each other.

erelender
Can u pls explain?
Wondering
You may have a valid point - but without at least a little bit of explanation this kind of response is less than helpful. Its also at least a little bit wrong (since inheritance and interfaces are clearly related - at least in terms of the question).
Murph
You are right. I could be clearer. What i meant was, these concepts are not mutually exclusive. You can have both encapsulation and inheritance for example. Now i see that i understood the question wrong. I though OP was asking which to use. I didn't see that it was a test question. Sorry for the confusion.
erelender
+3  A: 

An interface will ensure that the class has method stubs for all the methods, but they may not be implemented and may throw NotImplementedExceptions.

A better way to ensure that all methods are implemented would be using unit tests where you check that the methods actually do what they should.

Rune Grimstad
The problem with saying "use unit tests" is that its rather dependent on the context in which the question is asked... if you're asking "have I implemented all methods" then yes, probably. If, on the other hand, you're saying "I want to ensure that someone implementing 'this' has provided all the necessary methods" then its a rather different issue.
Murph
+4  A: 

An interface or an abstract class will accomplish what you want. In an abstract class, if a method is marked as abstract, then it must be implemented in the derived class. The question really comes down to which one you should use. An interface, or an abstract class.

The quick answer (and I do mean quick and dirty) is that you should use an interface when you are trying to set up contractual behavior between classes. You should use an abstract class when the set of derived class have some shared behavior.

Amir