C# equivalent to implement interface inside super keyword in Java [duplicate] - java

I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.

C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.

This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.

If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.

you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}

myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.

In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :

Related

How to properly use a parameter of type class?

In java, I'd like to do something like this
public class Tata{
public static void f(){
//something
}
public static void g(){
//something
}
}
public class Titi{
public static void f(){
//something
}
public static void g(){
//something
}
}
public class Toto{
private Class c = Tata.class; //or Titi.class
public static void main(String[] args) {
c.f();
c.g();
}
}
To be precise, I'd like to be able to freely switch between classes Tata and Titi, to use their respective methods f or g.
This doesn't work as intended, as I get the cannot resolve method 'f()' error. Simply replacing c.f(); and c.g(); with Tata.f(); and Tata.g(); works fine, but defeats the purpose of using a parameter. How to solve this?
Will turn the comment into answer after all.. The correct (Java) way to deal with what you want is the use of interface. So in your demo code the implementation would be the following:
public interface TheFGFunctions {
void f();
void g();
}
public class Tata implements TheFGFunctions {
#Override
public void f() {
//something
}
#Override
public void g() {
//something
}
}
public class Titi implements TheFGFunctions {
#Override
public void f() {
//something
}
#Override
public void g() {
//something
}
}
public class Toto {
private TheFGFunctions c;
public Toto(TheFGFunctions c) {
this.c = c;
}
public void notStaticFunction() {
c.f();
c.g();
}
}
This way is totally typesafe with zero exceptions to deal with!
You cannot access a static method polymorphically. The Java language doesn't support it.
The reason your current approach fails is that c is an instance of the class Class, and the class Class doesn't define methods f() or g().
(The methods that it does define are listed in the javadoc for Class. Note that Class is final so you can't create a custom subclass with extra methods.)
The simple alternative is to use reflection; e.g.
Class c =
Method f = c.getMethod("f");
f.invoke(null); // because it is static
But note:
This is not statically type-safe. The compiler cannot tell when you make the mistake of trying to use a static f() on a class that doesn't have such a method.
There are a few exceptions that you need to deal with; e.g. missing methods, incorrect signatures, methods that are not static, methods that don't have the correct access.
Other answers have proposed creating an interface and wrapper classes to make certain static methods dispatchable. It will work and it will be compile-time type-safe (!) but there is a lot of boiler plate code to write.
#Michael Michailidis commented:
Thus interfaces!
Yea ... kind of. You can only dispatch polymorphically on instance methods declared on an interface. That implies that you must have an instance of Tata or Titi, and call the methods on it. My reading of the Question is that the author wants to avoid that.
(IMO, the avoidance is the real problem. You are better of not trying to avoid instance methods.)
FWIW, you can declare static methods in an interface (since Java 8), but they would behave the same as if you declared them in a class. You wouldn't be able to dispatch ...
You could use reflections:
private Class c = Tata.class;
public Toto() throws Exception {
c.getMethod("f").invoke(null);
c.getMethod("g").invoke(null);
}
Here my Tata class
public class Tata {
public static void f() {
System.out.println("ffff");
}
public static void g() {
System.out.println("gggg");
}
}
Output on new Toto() call:
ffff
gggg
Update (call with parameters):
public Toto() throws Exception {
c.getMethod("f", String.class).invoke(null, "paramValue1");
c.getMethod("g", String.class).invoke(null, "paramValue2");
}
public class Tata {
public static void f(String param1) {
System.out.println("ffff " + param1);
}
public static void g(String param2) {
System.out.println("gggg " + param2);
}
}
Output:
ffff paramValue1
gggg paramValue2
Write a wrapper interface
interface CWrapper {
void f();
void g();
}
and wrapper class factory method for each Class containing the methods
class CWrappers {
CWrapper forTiti(Class<Titi> titiClass) {
return new CWrapper() {
void f() { Titi.f(); }
void g() { Titi.g(); }
}
}
// another factory method for Tata
}
Then you can use that:
public class Toto {
private CWrapper c = CWrappers.forTata(Tata.class); //or forTiti(Titi.class)
public static void main(String[] args) {
c.f();
c.g();
}
}

Can I use default method in is override? [duplicate]

Java 8 introduces default methods to provide the ability to extend interfaces without the need to modify existing implementations.
I wonder if it's possible to explicitly invoke the default implementation of a method when that method has been overridden or is not available because of conflicting default implementations in different interfaces.
interface A {
default void foo() {
System.out.println("A.foo");
}
}
class B implements A {
#Override
public void foo() {
System.out.println("B.foo");
}
public void afoo() {
// how to invoke A.foo() here?
}
}
Considering the code above, how would you call A.foo() from a method of class B?
As per this article you access default method in interface A using
A.super.foo();
This could be used as follows (assuming interfaces A and C both have default methods foo())
public class ChildClass implements A, C {
#Override
public void foo() {
//you could completely override the default implementations
doSomethingElse();
//or manage conflicts between the same method foo() in both A and C
A.super.foo();
}
public void bah() {
A.super.foo(); //original foo() from A accessed
C.super.foo(); //original foo() from C accessed
}
}
A and C can both have .foo() methods and the specific default implementation can be chosen or you can use one (or both) as part of your new foo() method. You can also use the same syntax to access the default versions in other methods in your implementing class.
Formal description of the method invocation syntax can be found in the chapter 15 of the JLS.
This answer is written mainly for users who are coming from question 45047550 which is closed.
Java 8 interfaces introduce some aspects of multiple inheritance. Default methods have an implemented function body. To call a method from the super class you can use the keyword super, but if you want to make this with a super interface it's required to name it explicitly.
class ParentClass {
public void hello() {
System.out.println("Hello ParentClass!");
}
}
interface InterfaceFoo {
public default void hello() {
System.out.println("Hello InterfaceFoo!");
}
}
interface InterfaceBar {
public default void hello() {
System.out.println("Hello InterfaceBar!");
}
}
public class Example extends ParentClass implements InterfaceFoo, InterfaceBar {
public void hello() {
super.hello(); // (note: ParentClass.super could not be used)
InterfaceFoo.super.hello();
InterfaceBar.super.hello();
}
public static void main(String[] args) {
new Example().hello();
}
}
Output:
Hello ParentClass!
Hello InterfaceFoo!
Hello InterfaceBar!
The code below should work.
public class B implements A {
#Override
public void foo() {
System.out.println("B.foo");
}
void aFoo() {
A.super.foo();
}
public static void main(String[] args) {
B b = new B();
b.foo();
b.aFoo();
}
}
interface A {
default void foo() {
System.out.println("A.foo");
}
}
Output:
B.foo
A.foo
You don't need to override the default method of an interface. Just call it like the following:
public class B implements A {
#Override
public void foo() {
System.out.println("B.foo");
}
public void afoo() {
A.super.foo();
}
public static void main(String[] args) {
B b=new B();
b.afoo();
}
}
Output:
A.foo
It depends on your choice whether you want to override the default method of an interface or not. Because default are similar to instance method of a class which can be directly called upon the implementing class object. (In short default method of an interface is inherited by implementing class)
Consider the following example:
interface I{
default void print(){
System.out.println("Interface");
}
}
abstract class Abs{
public void print(){
System.out.println("Abstract");
}
}
public class Test extends Abs implements I{
public static void main(String[] args) throws ExecutionException, InterruptedException
{
Test t = new Test();
t.print();// calls Abstract's print method and How to call interface's defaut method?
}
}

C# Initialize abstract class like Java

In Java I'm able to have a class like this:
public abstract class Button{
public abstract void onClick();
}
Then initialize it by using:
Button b = new Button(){
#Override
public void onClick(){
// Things
}
}
Now is there any way to do a similar thing in C#?
Or would my best bet be to use an event?
If you want to use Abstract Class you need to have another class inherited from that Abstract Class and use it to initialize abstract class like this:
public class MeSecondClass : MyClass
{
public override void OnClick(object sender, EventArgs args)
{
throw new NotImplementedException();
}
}
public abstract class MyClass
{
public abstract void OnClick(object sender, EventArgs args);
}
MyClass a = new MeSecondClass();
The comparable approach in C# to Java's anonymous inner classes feature is to instantiate a dynamic object and convert it to the abstract class. Unfortunately you have to implement the conversion yourself.
Example:
using System;
namespace AnonymousInnerClassExample
{
class Program
{
public static void Main(string[] args)
{
Button button = Button.CreateFromDynamic(new
{
OnClick = new Action(() =>
{
Console.WriteLine("Hit OnClick");
})
});
button.OnClick();
}
public abstract class Button
{
public abstract void OnClick();
public static Button CreateFromDynamic(dynamic button)
{
return new Implementation(button);
}
private class Implementation : Button
{
public Implementation(dynamic button)
{
PrivateOnClick = button.OnClick;
}
private Action PrivateOnClick { get; set; }
public override void OnClick()
{
PrivateOnClick();
}
}
}
}
}
Just for anyone else trying to do something similar. #shmosel suggested lambdas, and so that is what I used.
public class Button(){
private Action _onClick;
public Button(Action onClick){
_onClick = onClick;
}
//Other method that calls _onClick()
}
//Other Class
Button b = new Button(() => {/*Do Code Here*/});
As the other answers show, you CAN do something similar, but really the question is 'Should you?' and the answer is no.
Events were created for just this sort of thing, so use an event. Not only is it clearer and cleaner code, but it is a well established pattern that C# devs will know, so using it help with maintainability of your code.

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

An anonymous class can extend only from one class or interface, so I can't do the next :
interface Enjoyable {
public void enjoy();
}
interface Exercisable {
public void exercise();
}
public class Test {
public static void main(String[] args) {
new Enjoyable implements Exercisable() {
public void enjoy() {
System.out.println(":D");
}
}.enjoy();
}
}
It says that :
Enjoyable.Exercisable cannot be resolved to a type
I'm trying to replicate this behavior and I wrote the next code:
interface Enjoyable {
interface Exercisable {
public void exercise();
}
public void enjoy();
}
public class Test {
public static void main(String[] args) {
new Enjoyable.Exercisable() {
public void enjoy() {
System.out.println(":D");
}
public void exercise() {
System.out.println("Doing exercise !!!");
}
}.exercise();
new Enjoyable.Exercisable() {
public void enjoy() {
System.out.println(":D");
}
public void exercise() {
System.out.println("Doing exercise !!!");
}
}.enjoy();
}
}
And then I get :
Doing exercise !!! :D
Are there another way to simulate It?
And way i hace to implement both metods un the anonymous class ?
Thanks
I want an anonymous class who implements 2 interfaces methods
I assume you mean you want an anonymous class which implements two interfaces. You can't, directly.
You can do
interface EnjoyableAndExercisable extends Enjoyable, Exercisable {
}
and then create an anonymous class that implements that.
EnjoyableAndExercisable o = new EnjoyableAndExercisable() {
#Override
public void enjoy() {
System.out.println(":D");
}
#Override
public void exercise() {
System.out.println("Doing exercise !!!");
}
};
Note the #Override which will always validate whether you are actually overriding a method or not.
In your code however, this anonymous class
new Enjoyable.Exercisable() {
public void enjoy() {
System.out.println(":D");
}
public void exercise() {
System.out.println("Doing exercise !!!");
}
}.enjoy();
is only an implementation of Exercisable. You just happen to declare a method with the name enjoy within it.
You cannot assign it to a variable of type Enjoyable
Enjoyable ref = new Enjoyable.Exercisable() {
public void enjoy() {
System.out.println(":D");
}
public void exercise() {
System.out.println("Doing exercise !!!");
}
}; // nope, compile time error
You can only invoke that method on the new instance creation expression that declares this anonymous type. You cannot invoke it any other way (since it's declared in an anonymous type).
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.
You can create anonymous inner classes based on a non-final class or an interface with
new Exerciseable(){
...
}
However, Java does not allow
new Object() implements Exercisable{
...
}
or
new Object implements Exercisable(){
...
}
The anonymous inner class produces with the new keyword a new instance of a class whose superclass is Object and implements Exercisable. The JCP site hosts a document (https://jcp.org/aboutJava/communityprocess/maintenance/JLS/innerclasses.pdf), belonging to the JSL about inner classes which says:
As already hinted, if an anonymous class is derived from an interface
I, the actual superclass is Object, and the class implements I rather
than extending it. (Explicit implements clauses are illegal.) This is
the only way an interface name can legally follow the keyword new. In
such cases, the argument list must always be null, to match the
constructor of the actual superclass, Object.
Your second example constructs a type Exercisable which extends Enjoyable. Creating anonymous classes of that interface is legal again.

java 8 event listener/dispatcher using lambdas/method references - how to achieve certain things?

I'm trying to write an event engine in Java using the newly added lambdas. I would very much like it if the following code would work:
public class Test
{
public Test()
{
EventEngine.listen(EventType.THIS, self::thisEventCallback);
EventEngine.listen(EventType.THAT, self::thatEventCallback);
EventEngine.listen(EventType.OTHER, (other) -> other.doX());
}
private void thisEventCallback()
{
// do whatever here
}
private boolean thatEventCallback(SomeObject parameter)
{
return parameter.someCheckOrWhatever();
}
}
As far as I understand, I would have to define a generic empty interface, for example, public interface Listener {// nothing here}, and extend it via various other interfaces for each event type so I can specify different parameters and return types where necassary.
Obviously, that would require casting the callbacks to the specific interface inside the EventEngine's trigger method(s), but I have no problem with that.
However, before that I need to find out how to reference these private methods I have defined to the EventDispatcher.listen method. self::thisEventCallback doesn't work. Is there even a way to do this in Java 8 or is it only possible in Scala?
If not, then what would you suggest as a replacement that does not involve creating a new object for every listener/callback?
EventEngine.listen(EventType.THIS, this::thisEventCallback);
EventEngine.listen(EventType.THAT, this::thatEventCallback);
EventEngine.listen(EventType.OTHER, (other) -> other.doX());
So this instead of self.
And you need functional interfaces with one abstract method having the same signature as the callback.
public interface THISInterface {
public void thisEventCallback();
}
public interface THATInterface {
public boolean thatEventCallback(SomeObject parameter)
}
class EventEngine {
public void listen(Type t, THISInterfcace thisCallback) {
thisCallback.thisEventCallback();
}
public void listen(Type t, THATInterfcace thatCallback) {
boolean ok = thatCallback.thatEventCallback();
}
...
}
However there are already many functional interfaces predefined, which you should need to learn. For instance here, one would not need own interfaces.
class EventEngine {
public void listen(Type t, Consumer<Void> thisCallback) {
thisCallback.accept();
}
public void listen(Type t, Predicate<Void> thatCallback) {
boolean ok = thatCallback.test();
}
Whether the above is correct, I am not sure (at the moment deep in java 6 - sigh).
Instead of creating sub-interfaces adding new methods to a base interface you can define a conventional listener interface (like, say MouseListener) having multiple call-back methods and create sub-interfaces overriding all but one method with empty default methods for the sole purpose of allowing lambda implementations of the remaining single abstract method. They replace what classes like MouseAdapter did for previous Java versions (when using anonymous inner classes):
interface AllPurposeListener {// the only one our engine uses internally
void caseOne(int arg);
void caseTwo(String arg);
}
interface CaseOneListener extends AllPurposeListener {
#Override public default void caseTwo(String arg) {}
}
interface CaseTwoListener extends AllPurposeListener {
#Override public default void caseOne(int arg){}
}
// Of course, I over-simplify the engine’s listener registry here
AllPurposeListener listener;
public void listen(AllPurposeListener l) {
listener=l;
}
public void listen(CaseOneListener l) {
listener=l;
}
public void listen(CaseTwoListener l) {
listener=l;
}
private void foo(int i) { }
private void bar(String s) { }
void doRegistration() {
listen(this::foo);// register for case one
listen(this::bar);// register for case two
listen(new AllPurposeListener() { // for all cases
public void caseOne(int arg) {
}
public void caseTwo(String arg) {
}
});
}

Categories