在C#和Java中实现接口的不同方法

时间:2018-07-19 07:00:54

标签: java c# interface implements

java 中,我可以通过以下两种方式实现

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");

}


}

我也知道以这种方式在C#中实现 文件-https://docs.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;
}
}

但是我想以在 Main.java

中所做的方式实现它

C#中,我找不到任何无需创建额外方法的方法。

0 个答案:

没有答案