-1

While learning about interface reference types I was playing around and found something odd; the code below. As you see, the line with "ibs.spaceOther(); " is confusing me.

Could someone point me in the right direction? Maybe give me a word or something for me to google?

// IBlockSignal.java
public interface IBlockSignal {
    public void denySignal();
}

// SpaceTechnology.java
public class SpaceTechnology implements IBlockSignal {
    @Override
    public void denySignal() {
        System.out.println("space-deny");
    }
    public void spaceOther(){
        System.out.println("space-other");
    }
}

// Main.java
public class Main {
    public static void main(String[] args) {
        IBlockSignal ibs;
        ibs = new SpaceTechnology();
        ibs.denySignal();
        System.out.println(ibs.getClass());
        // ibs.spaceOther(); // <--- Throws exception. Why? It is of class "SpaceTechnology". And this class does define spaceOther()        
        ((SpaceTechnology) ibs).spaceOther();
    }
}


////////////////////////////////////////
// Output:
//
// space-deny
// class SpaceTechnology
// space-other

  • https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html – Arvind Kumar Avinash Jul 22 '20 at 18:13
  • 2
    The compiler only knows that `ibs` is of type `IBlockSignal`, which doesn't have a `spaceOther` method. That the *actual* (runtime) time is `SpaceTechnology`, is coincidence, as far as the compiler is concerned. – MC Emperor Jul 22 '20 at 18:15
  • By casting, you say to the compiler "trust me, I know more than you, just assume this is a `SpaceTechnology`". – MC Emperor Jul 22 '20 at 18:20

1 Answers1

1

ibs.spaceOther() doesn't throw an exception. It doesn't compile.

Because you are using an interface reference, which only has access to the left-hand side type's methods

https://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245