1

In java I can implement in following two ways :

package com.company;
class ToInherit {

public interface MyInterface {
    void methodInInterface(boolean isError, String text);
}
}

Main.java

package com.company;

public class Main {

public static void main(String[] args) {
    // write your code here

    Main mainObj = new Main();

    mainObj.MyMethod(new ToInherit.MyInterface() {
        @Override
        public void methodInInterface(boolean isError, String text) {
            // My Task Here
        }
    });


}

private void MyMethod(ToInherit.MyInterface myInterface) {

    myInterface.methodInInterface(true, "Text");

}

}

Main2.java

package com.company;

public class Main2 implements ToInherit.MyInterface {

public static void main(String[] args) {
    // write your code here
    Main2 main2Obj = new Main2();
    main2Obj.MyMethod(main2Obj);


}

@Override
public void methodInInterface(boolean isError, String text) {
    // My Task Here
}

private void MyMethod(ToInherit.MyInterface myInterface) {

    myInterface.methodInInterface(true, "Text");

}


}

I also know that implementing in C# in this way from Docs - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/

public class Car : IEquatable<Car>
{
public string Make {get; set;}
public string Model { get; set; }
public string Year { get; set; }

// Implementation of IEquatable<T> interface
public bool Equals(Car car)
{
    return this.Make == car.Make &&
           this.Model == car.Model &&
           this.Year == car.Year;
}
}

But I want to implement it in the way I did in Main.java

I didn't find any way to do in such way in C# without creating an extra method.

Pishang Ujeniya
  • 176
  • 5
  • 13
  • 1
    "without creating an extra class" That´s not possible, only **classes** can implement interfaces. Even Java has this restriction, however the compiler is able to crfeate one for you in the background. If your interface has only a single method you could use a delegate however. – MakePeaceGreatAgain Jul 19 '18 at 07:04
  • @HimBromBeere Thank you so much for the explanation. – Pishang Ujeniya Jul 19 '18 at 07:10

0 Answers0