简体   繁体   中英

If a class is using an interface, it must

If a class is using an interface, it must:

  • (1) inherit the properties of the interface

  • (2) contain the same methods as the interface

  • (3) create an interface object

  • (4) all of the above

And the correct answer is (4) .

Note: this comes from here and I have no idea who actually is the author of the question.

I agree to the (1)st and (2)nd, but I would argue over the wording of the (3)rd.

I guess it could be dually interpreted;

Create an interface object could mean just an instance of a class that inherits an interface

or

A reference variable of the Interface type


What is the correct way of interpreting the above?

Would the below make sense?

If a class is using an interface, it must:

  • (1) inherit the properties of the interface

  • (2) provide implementation for all methods that the interface exposes

  • (3) ???

  • (4) all of the above

(2) provide implementation for all methods that the interface exposes

No. Abstract classes can implement an interface without providing an implementation (they still have to declare the methods defined in the interface, but they don't have to provide a body).

I wouldn't know how to interpret number 3 either though. When looking trough the link you have provided it's just a matter of badly worded questions. I'm still trying to figure out what this means:

  1. What is the output of the code public class B : A { }
    • Errors
    • It defines a class that inherits the public methods of A only.
    • It defines a class that inherits all the methods of A but the private members cannot be accessed.
    • b and c

I think you simply misread something. What I see that text as telling me is that

(1) to implement a class so that you can create an object that is an instance of that class, every method of the class and the implemented interfaces must be concrete -- must be fully implemented.

(2) Because interfaces are associated with object instances, an object instance must actually exist before you can access the associated methods.

I'm not really seeing it saying anything deeper or distinct. The line you asked about seems to be making just this second point: to actually use the interface methods, you need to have an object of the associated class on which the methods can be invoked.

This is because an interface in C# doesn't support static methods. So all methods are instance methods... and so one can't "use" the interface without having an associated object -- an instance of the interface, or an "interface object" as they seem to be using that term here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM