Java – same methods in children, not in Parent

I have an interface, such as:

public interface IParent   {
}

And then:

public interface IClassA extends IParent {

    @Nonnull
    IClassAKind getKind ();


    @Nonnull
    @Nonempty
    default String getKindID ()
    {
        return getKind ().getID ();
    }
}

And a second one similar:

public interface IClassB extends Parant {
    
    @Nonnull
    IClassBKind getKind ();
  
    @Nonnull
    @Nonempty
    default String getKindID ()
    {
        return getKind ().getID ();
    } 
}

So both child interfaces have the same methods but not the parent.

The issue is when I have an instance, that can be of any type, but I want to call the getKind().

As for now I do:

      IParent  aCurrentObject = getImplementation();
      IClassKind kind = null;
      if(aCurrentObject instanceof IClassA){
        kind = ((IClassA) aCurrentObject).getKind();
      } else {
        kind = ((IClassB) aCurrentObject).getKind();
      }

I’m doing these if and casing too many times in the code.
Any idea how to make it nicer?

>Solution :

It looks that you have an issue with IClassAKind and IClassBKind. So, I think you need something like this

public interface IClassKind {
    IClassKind getKind();
}

class IClassAKind implements IClassKind {

    @Override
    public IClassAKind getKind() {
        // return A-Kind object
    }
}

class IClassBKind implements IClassKind {

    @Override
    public IClassBKind getKind() {
        // return B-Kind object
    }
}

So, after his change, your could will be without any casting

IParent aCurrentObject = getImplementation();
IClassKind kind = kind = aCurrentObject.getKind();

Also, need to update IClassA and IClassB to use the interface IClassKind instead of a concrete class. For example

public interface IClassA extends IParent {

    @Nonnull
    IClassKind getKind();
    
    // ... 
}

Leave a Reply