Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>An alternative in C# (and may exist in Java, but I'm not a Java person so I don't know) is interfaces.</p> <pre><code>public interface C { int SomeMethodInC(); } public class A { } public class B : A, C { } ... in other class.... B someB = new B(); i someInt = someB.SomeMethodInC(); </code></pre> <p>It looks like multiple inheritance, but it isn't. Interface C defines the signature for someMethodInC, but not the implementation. Class B will have to implement someMethodInC.</p> <p>In C#, you can inherit from only one class, but you can inherit multiple interfaces. (Same in Java, I think.)</p> <p>In C#, you can also attach implementations to interfaces by using extension methods.</p> <pre><code>public static class CExtensions { public static int SomeExtensionToC(this C someC, int someInt) { return someInt * 2; } } ... in code ... B objB = new B(); y = objB.SomeExtensionToC(x); </code></pre> <p>Both the method and implemention of SomeExtensionToC will be available to any class that inherits <code>interface C</code>. Note that both the class and method are static, and that the first parameter includes the keyword "this" in reference to an object implementing C. Some parts of the .NET framework (LINQ, as an example) are implemented as extension methods to <code>IEnumerable&lt;T&gt;</code>.</p> <p>Almost like multiple inheritance, without the bad parts. And the extension methods are still considered part of the interface, so can be considered as part of the "contract" inherent in interface C.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload