Can Anonymous Class Implement Interface

Can anonymous class implement interface?

No, anonymous types cannot implement an interface. From the C# programming guide:

Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

Create anonymous class that implements an interface

Sorry, no inline implementation of classes in C#. There are only Anonymous Types, but they don't support adding interfaces (see for example Can a C# anonymous class implement an interface?) (nor they support adding methods or fields... They only support properties).

You can use the methods of System.Reflection.Emit to generate a class at runtime, but it's long and tedious.

c# Anonymous Interface Implementation

The general way to do this is C# is to create your own private class. As you noted, other approaches in C# (delegate/lambda) only work when the interface has just one method (i.e., a Java functional interface):

Java:

void testMethod()
{
x = new ISomeInterface(){
@Override
public void method1() { foo(); }
@Override
public void method2() { bar(); }
};
}

C#:

void testMethod()
{
x = new ISomeInterfaceAnonymousInnerClass();
}

private class ISomeInterfaceAnonymousInnerClass : ISomeInterface
{
public void method1()
{
foo();
}
public void method2()
{
bar();
}
}

Here is the simplest conversion when a Java functional interface is involved:

Java:

@FunctionalInterface
interface ISomeInterface
{
void method();
}

void testMethod()
{
x = new ISomeInterface(){
@Override
public void method() { foo(); }
};
}

C#:

delegate void ISomeInterface();

void testMethod()
{
x = () =>
{
foo();
};
}

Java Anonymous Class with Interface

I'll assume public check() was a typo.

  1. i really dont get, WHY the method someFunction() expects a Interface as parameter

Why not? Your interface is Checker and your method signature is

public someFunction(List param1, Checker param2)

The second argument takes a Checker.


  1. i also dont understand WHY i can pass an instance of an interface to that function (in main()).

You aren't passing an instance of an interface. You are passing an anonymous class. When you say:

new Checker(){
...
//[implementation of interface]
...
});

you are implementing the interface.

C# equivalent of creating anonymous class that implements an interface

Woof...ok, permit me to generalize a bit:

So in Java, you need a way to pass functions around. Java does not inherently support functions as first-class citizens, and this was one reason behind the implementation of anonymous classes - packaged groups of functions that can be declared inline and passed (as interfaces) to methods/other classes that will then call these functions.

In C#, functions are first-class citizens, and can be declared as either Delegates, Func<>s, or Action<>s. Let's try a comparison (of sorts):

Some sort of Java-y construct (my Java's fairly old, so bear with me):

public interface IDoSomething {
public int Return42();
public bool AmIPrettyOrNot(string name);
public void Foo();
}

public void Main(String[] args) {
DoStuff(new IDoSomething() {
public int Return42() { return 42; }
public bool AmIPrettyOrNot(string name) { return name == "jerkimball"; }
public bool Foo(int x) { ... }
});
}

public void DoStuff(IDoSomething something) { ... }

The (very rough) equivalent of this in C# would be:

public void Main(string[] args)
{
Func<int> returns42 = () => 42;
Func<string,bool> amIPretty = name => name == "jerkimball";
Action<int> foo = x => {};
}

Now, as others have mentioned, you usually see this pattern on the Java side when dealing with the handling of events - likewise on the C# side:

 public class Foo 
{
// define the shape of our event handler
public delegate void HandlerForBarEvent(object sender, EventArgs args);
// declare our event
public event HandlerForBarEvent BarEvent;

public void CallBar()
{
// omitted: check for null or set a default handler
BarEvent(this, new EventArgs());
}
}

public void Main(string[] args)
{
var foo = new Foo();
// declare the handler inline using lambda syntax
foo.BarEvent += (sender, args) =>
{
// do something with sender/args
}
foo.CallBar();
}

Note that we can also give it something with the same "shape":

 public void MyHandler(object sender, EventArgs args)
{
// do stuff
}
public void Main(string[] args)
{
var foo = new Foo();
// that method above is the same "shape" as HandlerForBarEvent
foo.BarEvent += MyHandler;
foo.CallBar();
}

But it's also used in Java to define what Threads do, if memory serves (i.e., Runnable) - and we can do this as well in C#:

var thread = new Thread((Action)(() => 
{
// I'm the threads "run" method!
});
thread.Start();

Now, other stuff - enumeration:

public void processEvents(){
for(Event event : eventList)
eventList.execute();
}

C# has the same idea, just called differently:

public void processEvents()
{
// edit: derp, 'event' is a keyword, so I'm
// renaming this, since I won't get into why
// you could also use @event...
foreach(var evt in eventList)
{
evt.Execute();
}
}

Why an anonymous class can't implement two separated interfaces but can implement inner interfaces?

your Exercisable's are not Enjoyable :-)
nesting interfaces this way does not mean that the inner interface is
of the type of the outer interface !

you could just as well have written something like

new Object() {
public void enjoy() {
System.out.println(":D");
}

public void exercise() {
System.out.println("Doing exercise !!!");

}
}.enjoy()
// same for .excercise()

so you are not actually simulating an anonymous class that implements two interfaces.

you can see this when you actually try to assign your anonymous instance to a variable of a type of your interfaces

// this WILL NOT COMPILE !
Enjoyable enjoyable=new Enjoyable.Exercisable() {
public void enjoy() {
System.out.println(":D");
}

public void exercise() {
System.out.println("Doing exercise !!!");

}
}.enjoy();

you could of course do something like this :

interface Enjoyable {
public void enjoy();
}

interface Exercisable extends Enjoyable {
public void exercise();
}

and then create anonymous instances using those interfaces
Unfortunately creating an anonymous instance that implements two interfaces like you are trying to do is not possible.

Anonymous class implementing an interface

Looks like an IDE bug of some kind; Java's compiler is perfectly happy with it. If I set up that situation and use Oracle's Java8 javac, it compiles just fine.

It's fine here on IDEOne using non-public classes, or if I create these files and compile them:

Message.java:

public class Message { }

ObjectMessage.java:

public class ObjectMessage extends Message { }

Session.java:

public class Session { }

MessageFactory.java:

public interface MessageFactory<T extends Message> {

public T create(Session session);
}

MessageType.java:

public abstract class MessageType<T extends Message> implements MessageFactory<T>{

public static final MessageType<ObjectMessage> PLAYER_REGISTER = new MessageType<ObjectMessage>() {

@Override
public ObjectMessage create(Session session) { //Error, remove @Override annotation
return null;
}
};

private MessageType(){ }
}

Anonymous class implementing interface

No, this is not possible.

An anonymous type is meant to be a lightweight transport object internally. The instant you require more functionality than the little syntax provides, you must implement it as a normal named type.

Things like inheritance and interface implementations, attributes, methods, properties with code, etc. Not possible.



Related Topics



Leave a reply



Submit