Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
    
    // ... 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading