Java cast interface to class

26,468

Yes, that will work (if you change the declaration of cMyClass to implement iMyInterface) and it's safe so long as the reference really does refer to an instance of cMyClass.

However, it's a generally bad idea. The whole point of using an interface is to be able to work with any implementation - it's to separate the abstraction from the implementation. If you're then going to require a specific implementation, you might as well make the type of i just cMyClass to start with.

So suppose instead of calling the cMyClass constructor yourself, you receive a method parameter of type iMyInterface - it's a bad idea to cast to cMyClass at that point, as it could be a different implementation of the interface.

(On a separate note, it's a good idea to start following Java naming conventions, which state that classes and interfaces should be Pascal-cased - so ditch the c and i prefixes.)

Share:
26,468
TheFrancisOne
Author by

TheFrancisOne

Updated on July 05, 2022

Comments

  • TheFrancisOne
    TheFrancisOne almost 2 years

    I have a question about interface and class implementing interface.

    This is my code:

    interface iMyInterface {
        public iMethod1();
    }
    
    public class cMyClass implements iMyInterface {
        public iMethod1() {
            // some code
        }
        protected iMethod2() {
            // some code
        }
    }
    

    I would like to create an instance of iMyInterface as this :

    iMyInterface i = new cMyClass();
    i.iMethod1();
    

    It's ok, but how can I call iMethod2() from my interface instance? Is this working and safe:

    ((cMyClass)i).iMethod2();
    

    Thanks for help.

  • S.L. Barth
    S.L. Barth over 12 years
    I think that, if he's going to cast, he should verify the cast with instanceof, to be on the safe side.
  • Jon Skeet
    Jon Skeet over 12 years
    @S.L.Barth: Unless the desired failure mode is an ClassCastException anyway, of course, in which case an unconditional cast is fine.
  • TheFrancisOne
    TheFrancisOne over 12 years
    @Jon Skeet Thanks, I'm using it now including Method2 in interface. Sorry I forgot to add implements iMyInterface in my sample.
  • TheFrancisOne
    TheFrancisOne over 12 years
    Thanks, I add Method2 in my interface.