• Welcome to Valhalla Legends Archive.
 

Interfaces

Started by Imperceptus, September 25, 2009, 01:57 PM

Previous topic - Next topic

Imperceptus

I keep seeing references on msdn that some objects have interfaces, what are they good for?
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

Camel

Not sure if the mapping is 1:1, but in Java, an interface is one of the three base types (the others being classes and primitives). It is similar to a class in that it defines method signatures, but it does not define method bodies. You can not instantiate an interface.

Implementing an interface is similar to extension (aka inheritance), except that you're required to implement the methods defined. By contrast, when you extends a class, you may override non-final method behavior if you choose.

Objects of classes that implement an interface can be (implicitly or otherwise) cast to the interface's type. This is particularly useful if you have two classes that share common behavior, but are not have a super/sub-type relationship. For example, Jack and Jill might both be FictionalCharacters, but Jack does not extend Jill. Defining an inteface FictionalCharacter that Jack and Jill both implement allows reuse of code that operates on all FictionalCharacters.

interface FictionalCharacter {
    void goUpTheHill();
}

class Jack implements FictionalCharacter {
    void goUpTheHill() {
        ...
    }
}


HTH

pianka

It should also be noted that interfaces do not have state.  Nice example by the way :P

Imperceptus

What do you mean by they are stateless?  They have no constructor?
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

pianka

It is true that they have no constructor.  However, I meant that interfaces may not contain variables [except for constants, but these are usually inlined at compile time].  For instance in Camel's example we might want to store the age of Jack and Jill.  To do so we cannot just put an int into the interface.  In that situation, it would be better to use an abstract class.


MyndFyre

Interfaces also can contain properties, but they don't contain the implementation.

Ultimately, interfaces are one of the ways to prevent yourself from being tied to a specific implementation (the other being an inheritence tree).  In that way, they're great for defining points of extensibility.

Take BN#'s ICommandQueue interface for example:
QuoteImplements an outgoing command queue, which allows the client to delay, filter, or reorder messages that are waiting to be sent to prevent flooding. The default implementation does not delay or reorder messages.

BN# allows a programmer using BN# to create a bot to change the way that messages are sent.  By default, messages go through the DefaultCommandQueue, which lets a BattleNetClient know that a message is ready to be sent as soon as it is queued up.  JinxBot, on the other hand, implements a message queue using a timer

However, using this interface, developers can replace the standard command queue with something custom - for instance, a moderation plugin may replace the standard queue to prioritize /ban and /kick commands, or to obey the Priority parameter (which is ignored by default in the default and JinxBot implementations). 

So that's an example of how interfaces are used in an application or an API.  Interfaces tend to be preferred for methods of extensibility because they are multiply-inherited (whereas classes can only derive from a single immediate parent class).

Camel is correct in his analysis, though .NET supports five base types (classes, structs, enums, delegates, and interfaces).
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.

Imperceptus

Can you use multiple interfaces at the same level within an object?
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

MyndFyre

Quote from: Imperceptus on October 02, 2009, 04:29 PM
Can you use multiple interfaces at the same level within an object?

Yes.  That's what makes them more interesting than classes.

The primary difference between classes an interfaces is their semantic meaning.  A "class" has "behaviors" (methods) and "state" (data fields) attached to it.  An interface is really a contract that a specific class implements a specific behavior only.

An example illustrating the difference between C#/Java's implementation of interfaces and C++'s implementation of multiple inheritence might be in order.

Consider this C++ code:

class A
{
    public:
        int foo;
        void setFoo(int value) { foo = value; }
}

class B
{
    public:
        int foo;
        virtual void bar() = 0;
}

class C : public A, public B
{

}


Now, in this case, C has two copies of "foo" - one attached to the vtable of its A and one attached to B.  So to access its value, you have to qualify which one you're addressing:

C* item = new C;
item->foo = 10; // compiler error
(dynamic_cast<B>(item))->foo = 10; // now C's copy of B's foo is 10, but A's foo is still 0.


Java and C# avoid this by only allowing classes to have a single inheritance chain for classes - which means there isn't any ability of such a data collision to take place.

However, since the semantic meaning of an interface is to define behaviors, you can define any number of interfaces that have the same method names:

// Java
public interface A
{
    int getFoo();
}
public interface B
{
    int getFoo();
    void setFoo(int value);
}
public interface C
{
    void setFoo(int value);
}
public class ABC implements A, B, C
{
    private int _foo;
    public int getFoo() { return _foo; }
    public void setFoo() { _foo = value; }
}

This assumes that the semantic meanings of "getFoo" and "setFoo" are the same, but the implementing class only needs to implement the behaviors once.

(A little-known and rarely-used feature of) C# actually takes it a step further and allows you to explicitly implement an interface's behavior per-interface.  The theory is that you'd only call that method if you have a type reference to the interface, otherwise it won't be part of the class's actual use.  For instance, consider I used the same A, B, and C interfaces from above:


// C#
public class ABC : A, B, C
{
    private int _foo, _bar;
    public int getFoo() {  return _foo; }
    public void setFoo(int value) { _foo = value; }

    int B.getFoo()
    {
        return _bar;
    }

    void B.setFoo(int value)
    {
        _bar = value;
    }
}


If you have C# code that does this:

ABC obj = new ABC();
obj.setFoo(10);

The internal variable _foo will equal 10.  But, if you have this:
B obj = new ABC();
obj.setFoo(10);

The _bar variable will equal 10.

Explicitly-implemented interfaces are rarely useful, but they have their occasional value.  In 8 years, though, I think I've only used them maybe 3 or 4 times.  Your mileage may vary. :)
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.

Camel

Quote from: MyndFyre on September 30, 2009, 05:32 PM
Camel is correct in his analysis, though .NET supports five base types (classes, structs, enums, delegates, and interfaces).

In Java, enums are actually classes (which extend java.lang.Enum). Is it the same in .NET? It happens somewhat under the hood (the 'enum' keyword replaces the 'class' keyword), but it's still pretty clear what's happening there.

Structs and delegates simply don't exist there; structs are believed by the Java ideology to be poor design, and delegate functionality can be achieved by constructing an anonymous interface.


interface FictionalCharacter {
    void goUpTheHill();
}

void main() {
    FictionalCharacter jack = new FictionalCharacter() {
        void goUpTheHill() {
            ...
        }
    };
}

Imperceptus

nice explanation

ive found structs to always bite me in the ass down the road myself.  I do like how vb.net handles delegates though.
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

MyndFyre

Quote from: Camel on October 05, 2009, 12:48 PM
In Java, enums are actually classes (which extend java.lang.Enum). Is it the same in .NET? It happens somewhat under the hood (the 'enum' keyword replaces the 'class' keyword), but it's still pretty clear what's happening there.
Everything in .NET *always* ultimately extends System.Object - even type primitives and structs in .NET.  The CLR treats them semantically different, though.

* Classes are always allocated on the heap and have reference behavior; unless explicitly stated, they always derive from System.Object.
* Structures inherit from System.ValueType (a descendant of System.Object) and are always allocated on the stack and have copying behavior.
* Enums inherit from System.Enum (a descendant of System.ValueType) and are allocated on the stack, but are treated as numeric constants or literals (they are carried around as integers - even when compiled - and do not hold type information).
* Interfaces can be implemented by either classes or structures.
* Delegates derive from System.MulticastDelegate (then Delegate, then Object) and contain a function pointer and the "this" object.

So that was a long way to answer your question: no, it doesn't seem like they're the same.
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.

Imperceptus

I swear I learn more on these forums then I do from books
Quote from: Hazard on August 07, 2003, 03:15 PM
Highlight your entire code. Press the delete key. Start over again using Cuphead's CSB tutorial and work your way from their rather than raping code from downloaded sources meant purely for learning purposes. If this does not fix the problem, uninstall Visual Basic and get a new hobby. I suggest Cricket.

Camel

As a Java guy, that sounds awfully over-complicated for not much benefit. I'm sure that to you the Java way seems over-simplified, though. ;)

MyndFyre

Quote from: Camel on October 06, 2009, 05:24 PM
As a Java guy, that sounds awfully over-complicated for not much benefit. I'm sure that to you the Java way seems over-simplified, though. ;)

I think there are lots of good reasons for allowing stack-bound variables (for you they're primitives) to have functions.  Most specifically, they don't require any heap allocation or garbage collection - so if I call:


int x = 5;
Console.WriteLine(x.ToString());


My compiler isn't doing this:

int x = 5;
Integer @__x = new Integer(x);
Console.WriteLine(@__x.ToString());


(Of course when I started Java programming, you didn't get that automatic conversion, so it was even more annoying). ;-)

The advantage there is obviously less fragmentation that the garbage collector has to deal with.  There are additional benefits for the not-so-faint-of-heart as well, like the use of pointers to point to stack memory.  :)
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.

Camel

#14
Java doesn't auto-box the int either; it would use static String java.lang.Integer.toString(int). Auto-boxing only happens if you cast a primitive to a super-primitive.

And, for the record, this specific example would never be an issue anyways, because System.out.println(int) is one of the overloads. Additionally, the + operator for Strings and String.concat() have (int) overloads.