C# vs JAVA instance of Interface - 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

Listen to (register to) a specific method of interface without implement all the methods, Java

Interfaces are a good way to simulate callbacks. However, the class that implements an interface must override all the methods of this interface.
Now, I have an interface
interface MyInterface {
void callback1();
void callback2();
void callback3();
...
void callback100();
}
I want to make a listener that registers only for callback1(). Is there a way to listen to such an event without implementing the whole interface MyInterface ?
You can mark the methods that don't need to be implemented as default and give them an empty body. For example:
public class Main {
public static void main(String[] args) {
I i = new A();
i.f();
}
}
interface I {
default void f() {}
default void g() {}
}
class A implements I {
#Override
public void f() { // only implementing "f"
System.out.println("Hello");
}
}
If you can't use Java 8 features, you can create a separate interface for each callback:
interface Callback1Listener {
void callback1();
}
interface Callback2Listener {
void callback2();
}
interface Callback3Listener {
void callback3();
}
// ...
As alternative to Java 8 default method, you can look at the Adapter classes used in Swing listeners. It is a subclass that provides empty body for all methods of the interface. It allows to distinguish cases of you want an explicit definition of all method bodies and the case of you don't want necessarily to have behavior for all of them.
For example :
interface MyCallback {
void callback1();
void callback2();
void callback3();
}
And Adapter class :
public class MyAdapter implements MyCallback {
public void callback1(){}
public void callback2(){}
public void callback3(){}
}
Now client classes may use the interface or the adapter class to implement the callback :
MyCallBack callback = new MyAdapter(){
public void callback2(){
// I implement it only
}
}
Or :
MyCallBack callback = new MyCallBack(){
// I have to implement all
public void callback1(){
// ...
}
public void callback2(){
// ...
}
public void callback3(){
// ...
}
}
This is why it's a good idea to keep interfaces as simple as possible (and preferably use existing interfaces where possible).
Your example of an interface with 100 methods is known in expert circles as "Bad Design". It almost automatically results in bad code.

How to use Java Generics to enforce type restrictions

This question is a bit advanced so naturally also a little complicated. I will try and do my best to be as clear as possible.
As the title reads, I'd like to use Java Generics to enforce type restrictions when constructing an objects from some top level (main).
I have never really used Java generics but I found a pretty good use case for it which I am not sure how to implement.
I'd like to enforce type restriction when composing an object. Let me try to clarify with an example:
I have a top level main method here where I am evoking a NumberEngine object where I initialize and call methods of it. Notice when I call setExecuteBehavior(), I pass it an object of type RunNumberEvaluation (which along with RunStringEvaluation implements an interface called ExecutionBehavior).
As the name implies, NumberEngine works only with Numbers and not Strings, so it's inappropriate for me to pass setExecuteBehavior() an object of type RunStringEvaluation. How can I enforce this behavior at compile time?
public static void main(String[] args) {
NumberEngine numberEngine = new NumberEngine();
numberEngine.init("/path/to/forms");
numberEngine.getEngineVesion();
numberEngine.setExecuteBehavior(new RunNumberEvaluation);
numberEngine.performExecution();
// Here this should not compile, essentially throw me a compile error saying it can only accept
// an object of type RunNumberEvaluation, sincle NumberEngine can only run
// objects of type RunNumberEvaluation, etc...
numberEngine.setExecuteBehavior(new RunStringEvaluation());
numberEngine.performExecution();
}
So here I would like to basically make NumberEngine's setExecuteBehavior to only accept behavior which is relevent to it like the processing of data which pertains to numbers and not Strings. And vice-versa for StringEngine. I want StringEngine to only accept objects which pertains to Strings and not Numbers.
How can I accomplish this with Java generics?
I was thinking about something like this...
NumberEngine<? extends Numbers> extends Engine
Not even sure if this makes sense...
I have included working code below as an illustration of what I'm attempting to communicate.
I have an object of type Engine which is an abstract class with many extending concrete classes such as StringEngine, NumberEngine, et cetera. I have decoupled the algorithmic functionality into an interface with classes that implement that interface.
Base Abstract Class
public abstract class Engine {
ExecuteBehavior executeBehavior;
public void setExecuteBehavior(ExecuteBehavior executeBehavior) {
this.executeBehavior = executeBehavior;
}
public void performExecution() {
executeBehavior.execute();
}
public abstract void init(String pathToResources);
}
Concrete Implementing Class 1
public class StringEngine extends Engine {
public StringEngine() {
executeBehavior = new RunNumberEvaluation();
}
#Override
public void init(String pathToResources) {
System.out.println("Initializing StringEngine with resources "+pathToResources);
System.out.println("Successfully initialized StringEngine!");
}
}
Concrete Implementing Class 2
public class NumberEngine extends Engine {
public NumberEngine() {
executeBehavior = new RunStringEvaluation();
}
#Override
public void init(String pathToResources) {
System.out.println("Initializing NumberEngine with resources "+pathToResources);
System.out.println("Successfully initialized NumberEngine!");
}
}
Algorithm Interface
public interface ExecuteBehavior {
void execute();
}
Algorithm Implementation 1
public class RunNumberEvaluation implements ExecuteBehavior {
#Override
public void execute() {
// some processing
System.out.println("Running numeric evaluation");
}
}
Algorithm Implementation 2
public class RunStringEvaluation implements ExecuteBehavior {
#Override
public void execute() {
// some processing
System.out.println("Running string evaluation");
}
}
If you haven't noticed but here I'm making use of the strategy pattern where I segregate the varying algorithms into a family via interface from the static non-changing code.
Edit: I'd like to maintain the strategy pattern used here.
First put the "variable" classes into Engine's formal parmaeter list:
public abstract class Engine<B extends ExecuteBehavior> {
B executeBehavior;
public void setExecuteBehavior(B executeBehavior) {
this.executeBehavior = executeBehavior;
}
public void performExecution() {
executeBehavior.execute();
}
public abstract void init(String pathToResources);
}
Then you can define the subclasses the way you want:
public class StringEngine extends Engine<RunStringEvaluation> {
public StringEngine() {
executeBehavior = new RunStringEvaluation();
}
#Override
public void init(String pathToResources) {
System.out.println("Initializing StringEngine with resources "+pathToResources);
System.out.println("Successfully initialized StringEngine!");
}
}
In the example code you've provided, you don't need that. Just move setExecuteBehavior to the subclasses and make it private.
It's fairly simple to achieve that using generics, you were totally right trying to use generics for that
All you had to do is to change your classes like this
First the interface
public interface ExecuteBehavior<T> {
void execute();
}
Then the abstract implementation
public abstract class Engine<T> {
ExecuteBehavior<T> executeBehavior;
public void setExecuteBehavior(ExecuteBehavior<T> executeBehavior) {
this.executeBehavior = executeBehavior;
}
public void performExecution() {
executeBehavior.execute();
}
public abstract void init(String pathToResources);
}
And finally the RunNumberEngine and NumberEngine
public class RunNumberEvaluation implements ExecuteBehavior<Number> {
#Override
public void execute() {
// some processing
System.out.println("Running numeric evaluation");
}
}
NumberEngine
public class NumberEngine extends Engine<Number> {
public NumberEngine() {
executeBehavior = new RunNumberEvaluation();
}
#Override
public void init(String pathToResources) {
System.out.println("Initializing NumberEngine with resources "+pathToResources);
System.out.println("Successfully initialized NumberEngine!");
}
}
And RunStringEngine, followed by StringEngine
public class RunStringEvaluation implements ExecuteBehavior<String> {
#Override
public void execute() {
// some processing
System.out.println("Running string evaluation");
}
}
StringEngine
public class StringEngine extends Engine<String> {
public StringEngine() {
executeBehavior = new RunStringEvaluation();
}
#Override
public void init(String pathToResources) {
System.out.println("Initializing StringEngine with resources "+pathToResources);
System.out.println("Successfully initialized StringEngine!");
}
}

Java multi-type method parameter?

I wonder if it is possible to require that a java method parameter is of any type from finite set of types. For example - I am using a library where two (or more) types have common methods, but their lowest common ancestor in the type hierarchy is Object. What I mean here:
public interface A {
void myMethod();
}
public interface B {
void myMethod();
}
...
public void useMyMethod(A a) {
// code duplication
}
public void useMyMethod(B b) {
// code duplication
}
I want to avoid the code duplication. What I think of is something like this:
public void useMyMethod(A|B obj){
obj.myMethod();
}
There is similar type of syntax in java already. For example:
try{
//fail
} catch (IllegalArgumentException | IllegalStateException e){
// use e safely here
}
Obviously this is not possible. How can I achieve well designed code using such type of uneditable type hierarchy ?
What about passing the function as a parameter to your useMyMethod function?
If you are using Java < 8:
public interface A {
void myMethod();
}
public interface B {
void myMethod();
}
public void useMyMethod(Callable<Void> myMethod) {
try {
myMethod.call();
} catch(Exception e) {
// handle exception of callable interface
}
}
//Use
public void test() {
interfaceA a = new ClassImplementingA();
useMyMethod(new Callable<Void>() {
public call() {
a.myMethod();
return null;
}
});
interfaceB b = new ClassImplementingB();
useMyMethod(new Callable<Void>() {
public call() {
b.myMethod();
return null;
}
});
}
For Java >= 8, you could use Lambda Expressions:
public interface IMyMethod {
void myMethod();
}
public void useMyMethod(IMyMethod theMethod) {
theMethod.myMethod();
}
//Use
public void test() {
interfaceA a = new ClassImplementingA();
useMyMethod(() -> a.myMethod());
interfaceB b = new ClassImplementingB();
useMyMethod(() -> b.myMethod());
}
Try using Adapter design pattern.
Or, if it's possible, add some base interface:
public interface Base {
void myMethod();
}
public interface A extends Base {}
public interface B extends Base {}
...
public void useMyMethod(Base b) {
b.myMethod()
}
Also, you can use something similar to this
You could write an interface MyInterface with a single method myMethod. Then, for each type you want to consider as part of the finite set, write a wrapper class, like this:
class Wrapper1 implements MyInterface {
private final Type1 type1;
Wrapper1(Type1 type1) {
this.type1 = type1;
}
#Override
public void myMethod() {
type1.method1();
}
}
Then you just need to use a MyInterface rather than one of the finite set of types, and the appropriate method from the appropriate type will always get called.
Note that to actually use these wrapper classes to call the method myMethod you would have to write
myMethod(new Wrapper1(type1));
This is going to get a bit ugly as you are going to have to remember the name of the wrapper class for each type in the set. For this reason, you may prefer to replace MyInterfacewith an abstract class with several static factories that produce the wrapper types. Like this:
abstract class MyWrapper {
static MyWrapper of(Type1 type1) {
return new Wrapper1(type1);
}
static MyWrapper of(Type2 type2) {
return new Wrapper2(type2);
}
abstract void myMethod();
}
then you can call the method using the code
myMethod(MyWrapper.of(type1));
The advantage of this approach is that the code is the same no matter which type you use. If you use this approach you have to replace implements MyInterface in the Wrapper1 declaration with extends MyWrapper.
Well, the correct way to model your requirement would be to have myMethod() declared in a supertype interface C which both A and B extend; your method then accepts type C as its parameter. The fact that you have trouble doing this in the situation you describe indicates you are not modelling the class hierarchy in a way that actually reflects how they behave.
Of course, if you can't change the interface structure then you could always do it with reflections.
public static void useMyMethod(Object classAorB) throws Exception {
classAorB.getClass().getMethod("myMethod").invoke(classAorB);
}
This might not constitute a best practice, but could you make a new class (call it C), that contains the parts from A and B that are duplicated, and the make a new method that takes C, have your methods that take A and B make a C instance and call the new method?
So that you have
class C {
// Stuff from both A and B
}
public void useMyMethod(A a) {
// Make a C
useMyMethod(c);
}
public void useMyMethod(B b) {
// Make a C
useMyMethod(c);
}
public void useMyMethod(C c) {
// previously duplicated code
}
That would also let you keep any non duplicated code in the methods for A and B (if there is any).
This looks to me much like the template pattern:
public interface A {
void myMethod();
}
public interface B {
void myMethod();
}
public class C {
private abstract class AorBCaller {
abstract void myMethod();
}
public void useMyMethod(A a) {
commonAndUseMyMethod(new AorBCaller() {
#Override
void myMethod() {
a.myMethod();
}
});
}
public void useMyMethod(B b) {
commonAndUseMyMethod(new AorBCaller() {
#Override
void myMethod() {
b.myMethod();
}
});
}
private void commonAndUseMyMethod(AorBCaller aOrB) {
// ... Loads of stuff.
aOrB.myMethod();
// ... Loads more stuff
}
}
In Java 8 it is much more succinct:
public class C {
// Expose an "A" form of the method.
public void useMyMethod(A a) {
commonAndUseMyMethod(() -> a.myMethod());
}
// And a "B" form.
public void useMyMethod(B b) {
commonAndUseMyMethod(() -> b.myMethod());
}
private void commonAndUseMyMethod(Runnable aOrB) {
// ... Loads of stuff -- no longer duplicated.
aOrB.run();
// ... Loads more stuff
}
}
A dynamic proxy can be used to create a bridge between a common interface you define and the objects implementing the other interfaces that conform to the new interface. Then, you can have your useMyMethods convert the parameter to the new interface (as a dynamic proxy) and have your common code written in terms only of the new interface.
This would be the new interface:
interface Common {
void myMethod();
}
Then, with this invocation handler:
class ForwardInvocationHandler implements InvocationHandler {
private final Object wrapped;
public ForwardInvocationHandler(Object wrapped) {
this.wrapped = wrapped;
}
#Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Method match = wrapped.getClass().getMethod(method.getName(), method.getParameterTypes());
return match.invoke(wrapped, args);
}
}
You can have your methods like this:
public void useMyMethod(A a) {
useMyMethod(toCommon(a));
}
public void useMyMethod(B b) {
useMyMethod(toCommon(b));
}
public void useMyMethod(Common common) {
// ...
}
private Common toCommon(Object o) {
return (Common)Proxy.newProxyInstance(
Common.class.getClassLoader(),
new Class[] { Common.class },
new ForwardInvocationHandler(o));
}
Note that to simplify matters you could even elect one of your existing interfaces (A or B) to be used as the common interface.
(Look at another example here, and also at other ideas around this subject)
The correct way is to use Java Generics.
See http://docs.oracle.com/javase/tutorial/java/generics/bounded.html

How to pass Object Context to a callback interface in Java

Trying to get a handle on "callback interface". The concept as I understand it make sense except for the following
//FromSomeClass1
MyInterface conect;
public void setInterface(MyInterface myInter)
{
this.conect=myInter;
}
interface MyInterface
{
public void update(String str);
}
(Fuzziness starts here)
So when another class attempts to
//FromSomeClass2 implements MyInterface
...onCreate()
{
SomeClass1 newC = new SomeClass1()
newC.setInterface(this) ;
}
update(String str){
....code
}
this will not work because I am passing to a new object ? Unless I make the "conect" variable in Class1 static (Good Idea bad Idea...consequences ???)
Simply what is the correct way to pass the object back to "setInterface" method .
Hope that made sense and Thank You.
p.s.
To all those who want a good understanding of call backs this link will help.
Consider an example Animal interface with a single says(String) callback,
interface Animal {
public void says(String msg);
}
Next, let's add a class that uses the Animal interface to say something -
class Say {
public void say(Animal animal) {
animal.says("Bawk");
}
}
Now let's implement two different Animal(s) - we're going to have a Cow class and a Sheep class,
class Cow implements Animal {
public void says(String msg) {
System.out.printf("%s, I mean moo!%n", msg);
}
}
class Sheep implements Animal {
public void says(String msg) {
System.out.printf("%s, I mean baah!%n", msg);
}
}
Finally, to demonstrate the callback method we defined above -
public static void main(String[] args) {
Say say = new Say();
say.say(new Cow());
say.say(new Sheep());
}
Output is
Bawk, I mean moo!
Bawk, I mean baah!
Is not that you need to make it static. I mean, you could make everything in SomeClass1 and make the client register by calling an static method SomeClass1.setInterface(this)
I won't recommend doing that tough. This is an example fallowing your code:
import java.util.HashSet;
import java.util.Set;
public class CallbackExample {
interface MyInterface {
public void update(String str);
}
static class SomeClass1 {
private Set<MyInterface> connects = new HashSet<MyInterface>();
public void register(MyInterface myInter) {
this.connects.add(myInter);
}
public void doWork(String someParam) {
for (MyInterface myInterface : connects) {
myInterface.update(someParam);
}
}
}
static class SomeClass2 implements MyInterface {
public void onCreate(SomeClass1 caller) {
caller.register(this);
}
#Override
public void update(String str) {
System.out.println("Doing some logic in update for " + str);
}
}
public static void main(String[] args) {
// Caller and callback creation are decoupled
SomeClass1 caller = new SomeClass1();
SomeClass2 callback = new SomeClass2();
// alternative 1. Preferred
caller.register(callback);
// alternative 2. Fallowing your example
callback.onCreate(caller);
caller.doWork("param1");
}
}
A good example of the use of callbacks is the android-async-http library. To make a HTTP request, you call a method and pass in the details of the request along with an object that implements a certain callback interface. The request method returns immediately, but after the request is complete, the library's worker thread sets up a call in the main thread to a method on the callback object you provided.

How to subclass this without repeating code

I have class Dad with subclass Son. I'd like to create a subclass of Dad and a subclass of Son that overrides a method of Dad.
What would be the best way of doing this without repeating code? I can not modify Dad and Son.
Given...
public class Dad {
public void doSomething() {}
}
public class Son extends Dad {
}
...I'd like to create...
public class DadSubclass extends Dad {
#Overrides
public void doSomething() {
// My code
}
}
public class SonSubclass extends Son {
#Overrides
public void doSomething() {
// My code
}
}
...without repeating // My code.
The obvious solution would be to create a helper class and call it for both, but this is problematic if I want to call protected methods, and I'm not allowed to create the subclasses with the same package.
Is there a better solution?
Create a common helper class and call it.
Assuming your code isn't accessing member variables, I would just put this code in a static utility class. If this isn't the case, you can still do this by passing in a common superclass - that of 'Dad' public static void mycode(Dad d). If you need specific variables in the subclasses themselves, I would rethink your class structure.
What you really want here is something like this:
class DadSonSubclass extends Dad, Son {
public void doSomething() {
//mycode
}
}
This is multiple inheritance, which is not supported by Java. So your only option would be to create a helper/utility class, which is perfectly acceptable. If you need to call protected methods, just pass the Dad object in to the helper class and create public callback methods to access this info.
Maybe better, maybe not, depending on your point of view, but it can certainly be done. Put your code into a helper class, and use a callback to give that helper access to the protected methods it needs:
interface Callback {
void foo();
void bar();
void one();
void two();
}
class Helper {
static void helpMe(Callback callback) {
// My code
}
}
class DadSubclass extends Dad {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
DadSubclass.this.foo();
}
public void bar() {
DadSubclass.this.bar();
}
public void one() {
throw new UnsupportedOperationException("one() doesn't exist in Dad");
}
public void two() {
throw new UnsupportedOperationException("two() doesn't exist in Dad");
}
});
}
}
class SonSubclass extends Son {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
SonSubclass.this.foo();
}
public void bar() {
SonSubclass.this.bar();
}
public void one() {
SonSubclass.this.one();
}
public void two() {
SonSubclass.this.two();
}
});
}
}

Categories

Resources