Wondering
Wondering

Reputation: 5086

What do you use if you want to ensure that all methods and properties are implemented

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?

Upvotes: 2

Views: 4128

Answers (4)

Amir
Amir

Reputation: 9192

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.

Upvotes: 4

Rune Grimstad
Rune Grimstad

Reputation: 36310

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.

Upvotes: 3

zweihander
zweihander

Reputation: 6295

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

Upvotes: -1

Timothy S. Van Haren
Timothy S. Van Haren

Reputation: 8966

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."

Upvotes: 8

Related Questions