0

In a programming assignment we are not allowed to use lists, we only get to use arrays, however I have multiple classes and arrays for all of them that I want to check for a variable in them.

Foo f = new Foo();
Bar b = new Bar();

Foo[] fArray = new Foo[1];
fArray[0] = f;

CheckStatus(fArray);


public boolean CheckStatus<T>(T[] array) {

    if(array[0].IsTrue()) {
        return true;
    }

return false;

However, I only get the issue "cannot resolve symbol "IsTrue" I can get it to work by directly casting it to a Foo object but then it wont work with Bar etc.

It has worked great with the generics of for most other things such as extending array length but when I need to access the variables of the object I need to cast it and for that I will need specific if statements for each type of class my program has that I want to use with this method.

Thankful in advance for any help I can get here.

3
  • Probably simplest is to have a common interface for all classes that defines the common methods you need in the generic function Commented Mar 16, 2020 at 22:22
  • You'll need to show us the definitions of Foo and Bar. As @unholysheep points out, if both Foo and Bar have an IsTrue method of the same signature, create an interface (IFooOrBar) that has that method defined. Then declare both classes to implement that interface. Finally constrain T to be a type that implements the interface Commented Mar 16, 2020 at 22:28
  • Foo and Bar are basically identical objects, they have the same variable types and everything, its pretty much a copypaste of eachother. Refreshing my memory of how interfaces work as we speak and this looks very promising, especially since 3/3 people suggested it. Commented Mar 16, 2020 at 22:39

1 Answer 1

1

You will need an interface. And make your classes implement it.

public interface IMyObj
{
     bool IsTrue();
}

Then constraint your T type

public boolean CheckStatus<T>(T[] array) where T : IMyObj {...}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.