interfaces in java - MyClass is not abstract and does not override abstract method eq(Object) in MyClass error - interface

I know there is a Comparable interface, trying to figure out how to write my own.
Here's the interface
public interface MyComparable {
public boolean lt(Object other);
}
and a class that implements it and packages an int (yes, I know there is an Integer class)
public class MyInteger implements MyComparable {
private int value;
public MyInteger(int v)
{ value = v; }
public void set(int v)
{ value = v; }
public int get()
{ return value; }
public boolean lt(MyInteger other)
{ return get() < other.get(); }
}
I get " MyInteger is not abstract and does not override abstract method eq(Object) in MyInteger error". MyComparable doesn't declare an eq method. So it's comping from the superclass but I don't understand.

Related

Haxe access Class<T> static fields

I have three classes and I would like to be able to call static functions from the returned Class<Access>. I would like to select class type based on conditions.
class Access {
public static function get(item: Int): Int { return -1; }
public static function getAccessType(): Class<Access> {
if(Client.hasConnection())
return Remote;
else return Local;
}
}
class Remote extends Access {
override public static function get(item: Int): Int { return Server.getItem(item); }
}
class Local extends Access {
override public static function get(item: Int): Int { return Client.getItem(item); }
}
You can't override a static function in Haxe.
But you can probably achieve what you're trying to do by simply removing the override in Remote and Local
Can be done with singletons.
However, still the question might relevant whether such feature in Haxe even exists.
Depending on target, you may be able to cast a class to an interface/typedef to pull out values in a type-safe-ish way. "override" does not work for static methods
class Test {
static function pick(z:Bool):HasGetItem {
return z ? cast A : cast B;
}
static function main() {
trace("Haxe is great!");
trace(pick(false).getItem(1));
trace(pick(true).getItem(2));
}
}
#:keep class A {
public static function getItem(i:Int):Int return 10;
}
#:keep class B {
public static function getItem(i:Int):Int return 5;
}
typedef HasGetItem = {
getItem:Int->Int
}
https://try.haxe.org/#b2b87

How can I run a class method inside of a public void from a different class?

So I have a method like so (Method1):
public class Levels extends JFrame{
public void levelClass() {
if(menu.playerClass.equals("Warrior")) {
// I NEED COMMAND HERE
}
}
}
and I want to know how to run this class method (that is in a different class):
public class Classes {
public void listClasses() {
class Warrior { // THIS ONE
int health=100;
int evasionChance=20; // Percentage
int maxAttackDamage=30;
int minAttackDamage=25;
int numHealthPotions=2;
}
}
}
from the first code aka Method1.
Edit
DON'T
Change all:
public class Classes {
public void listClasses() {
class Warrior {
int health=100;
int evasionChance=20; // Percentage
int maxAttackDamage=30;
int minAttackDamage=25;
int numHealthPotions=2;
}
}
}
To:
public class Classes {
public void Warrior {
int health=100;
int evasionChance=20; // Percentage
int maxAttackDamage=30;
int minAttackDamage=25;
int numHealthPotions=2;
}
}
To call a method on a class, you need to instantiate the class.
public class Levels extends JFrame{
public void levelClass() {
if(menu.playerClass.equals("Warrior")) {
// instantiate the Classes class
Classes classes = new Classes();
// call the warrior method
classes.warrior();
}
}
}

resolve all given the Type

From the Autofac documentation I can see how to get all registrations for a class T:
public T[] ResolveAll<T>()
{
return _container.Resolve<IEnumerable<T>>().ToArray();
}
But when I only have the Type available, how can I get the equivalent results?
public Array ResolveAll(Type service)
{
return _container.Resolve( ???
}
I am trying to implement a wrapper class which has a pre-defined interface.
EDIT
For quick reference, the answer from Matthew Watson (with relevant ideas from David L) is:
public Array ResolveAll(Type service)
{
var typeToResolve = typeof(IEnumerable<>).MakeGenericType(service);
return _container.Resolve(typeToResolve) as Array;
}
Here is an example. I've added asserts to prove that the types returned from ResolveAll<T>(this IContainer self) are the same (and in the same order) as those returned from ResolveAll(this IContainer self, Type type):
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autofac;
using Autofac.Core;
namespace AutofacTrial
{
public abstract class Base
{
public abstract string Name { get; }
public override string ToString()
{
return Name;
}
}
public sealed class Derived1: Base
{
public override string Name
{
get
{
return "Derived1";
}
}
}
public sealed class Derived2: Base
{
public override string Name
{
get
{
return "Derived2";
}
}
}
public sealed class Derived3: Base
{
public override string Name
{
get
{
return "Derived3";
}
}
}
static class Program
{
static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<Derived1>().As<Base>();
builder.RegisterType<Derived2>().As<Base>();
builder.RegisterType<Derived3>().As<Base>();
var container = builder.Build();
var array1 = container.ResolveAll(typeof(Base));
var array2 = container.ResolveAll<Base>();
Trace.Assert(array1.Length == 3);
Trace.Assert(array2.Length == 3);
for (int i = 0; i < array1.Length; ++i)
{
Trace.Assert(array1[i].GetType() == array2[i].GetType());
Console.WriteLine(array1[i]);
}
}
public static T[] ResolveAll<T>(this IContainer self)
{
return self.Resolve<IEnumerable<T>>().ToArray();
}
public static object[] ResolveAll(this IContainer self, Type type)
{
Type enumerableOfType = typeof(IEnumerable<>).MakeGenericType(type);
return (object[]) self.ResolveService(new TypedService(enumerableOfType));
}
}
}
The underling implementation is the same
I also used Reflector to look at the implementation of Resolve<IEnumerable<T>>(), and it winds up doing this:
public static TService Resolve<TService>(this IComponentContext context, IEnumerable<Parameter> parameters)
{
return (TService) context.Resolve(typeof(TService), parameters);
}
which calls:
public static object Resolve(this IComponentContext context, Type serviceType, IEnumerable<Parameter> parameters)
{
return context.ResolveService(new TypedService(serviceType), parameters);
}
So the two must be equivalent, since they are implemented that way.
You can invoke _container.Resolve by calling your wrapped method via reflection (MSDN), but in doing so you will lose your compile-time type safety.
public class Container
{
public T[] ResolveAll<T>()
{
return _container.Resolve<IEnumerable<T>>().ToArray();
}
public object ResolveAllGeneric(Type t)
{
MethodInfo method = GetType().GetMethod("ResolveAll")
.MakeGenericMethod(new Type[] { t });
return method.Invoke(this, new object[] { });
}
}

Injecting a Factory that accepts a Parameter with AutoFac

I've read over several examples that were more complex then I needed and I'm having trouble distilling this down to a simple, concise pattern.
Let's say I have an interface names ICustomService and multiple implementations of ICustomService. I also have a class Consumer that needs to determine at run time which ICustomService to use based upon a parameter.
So I create a classes as follows:
public class Consumer
{
private CustomServiceFactory customServiceFactory;
public Consumer(CustomServiceFactory _customServiceFactory)
{
customServiceFactory = _customServiceFactory;
}
public void Execute(string parameter)
{
ICustomService Service = customServiceFactory.GetService(parameter);
Service.DoSomething();
}
}
public class CustomServiceFactory
{
private IComponentContext context;
public CustomServiceFactory(IComponentContext _context)
{
context = _context;
}
public ICustomService GetService(string p)
{
return context.Resolve<ICustomService>(p); // not correct
}
}
public class ServiceA : ICustomService
{
public void DoSomething()
{
}
}
public class ServiceB : ICustomService
{
public void DoSomething()
{
}
}
Is there an advantage to having my factory implement an interface? How do I fix my factory and register these classes with Autofac so that Consumer.Execute("A") calls DoSomething on WorkerA and Consumer.Execute("B") calls DoSomething on WorkerB?
Thank you
You would register your implementations of ICustomService with keys. For example:
builder.RegisterType<FooService>.Keyed<ICustomService>("someKey");
builder.RegisterType<BarService>.Keyed<ICustomService>("anotherKey");
and then your factory method would be:
public ICustomService GetService(string p)
{
return context.ResolveKeyed<ICustomService>(p);
}
But, you can take this a step further and decouple CustomServiceFactory from IComponentContext:
public class CustomServiceFactory
{
private Func<string, ICustomService> _create;
public CustomServiceFactory(Func<string, ICustomService> create)
{
_create = create;
}
public ICustomService GetService(string p)
{
return _create(p);
}
}
which you would register like so:
builder.Register(c => {
var ctx = c.Resolve<IComponentContext>();
return new CustomServiceFactory(key => ctx.ResolveKeyed<ICustomService>(key));
});
And at that point, assuming CustomServiceFactory doesn't have any other behavior that was omitted for the question, then you as might as well just use and register Func<string, ICustomService> directly.

C++/CLI: Cannot explicitly implement interface member with different return type

Let's say we have two C++/CLI interfaces declaring Foo() members with different return type.
public interface class InterfaceA
{
bool Foo();
};
public interface class InterfaceB
{
int Foo();
};
What we want to do here is to have a class that instantiates an object that can be accessed through the above interfaces. So, the straight forward way to do that would be:
public ref class Class : InterfaceA, InterfaceB
{
virtual bool Foo() = InterfaceA::Foo { return true; }
virtual int Foo() = InterfaceB::Foo { return 10; }
};
Unfortunately that gives us compiler error "overloaded function differs only by return type from". Is there any workaround for this C++/CLI limitation?
No, you have to rename the method. For example:
public ref class Class : InterfaceA, InterfaceB
{
public:
virtual bool Foo() { return true; }
virtual int Foo2() = InterfaceB::Foo { return 10; }
};
Note how this is never a real problem. If code has a reference to Class instead of the interface for some reason then it can always call InterfaceB::Foo() with a cast:
Class^ obj = gcnew Class;
safe_cast<InterfaceB^>(obj)->Foo();