I am trying to understand interfaces in Java and have this task to do which I am a stack with. It must be something easy, but I don’t seem to see the solution. Interface contains a few methods, one of them should return true if all elements of this set are also in the set. I.e.
public interface ISet{
//some methods
boolean isSubsetOf(ISet x);
}
Then the class:
public class myClass implements ISet{
ArrayList<Integer> mySet;
public myClass{
mySet = new ArrayList<Integer>();
}
//some methods
public boolean isSubsetOf(ISet x){
//method body
}
}
What do I need to write in method body? How do I check that the instance of myClass is a subset of ISet collection? I was trying to cast, but it gives an error:
ArrayList<Integer> param = (ArrayList<Integer>)x;
return param.containsAll(mySet);
An interface is like an idea of a class.
It contains things like method definitions and static and final variables.
Therefore any class that implements them will contain a body (i.e. a way to handle that method in this class).
For eg.
Now any class that implements this will “handle” the method isSubsetOf and return a boolean. How they do this is not the interfaces business.
Now in your class
This will work as we typecast x.mySet to ArrayList and x itself to myClass.
However there is a flaw in the logic. If you have another class implementing ISet then they might not typecast to myClass but in this case with on implements you will be fine.
It also seems like you are confused how to run this method so I’ll add that