bambo222
bambo222

Reputation: 429

Are interfaces like Abstract Classes in the sense that super-type methods work on class subtypes?

Consider the following statement: Suppose class A implements interface T. If you pass an object of type A to a method that expects an argument of type T, the code compiles but Java will throw a runtime exception.

I think this is FALSE. Don't interfaces behave like Abstract classes, so objects of type A are subclasses of type T (or do interfaces not have types?). If this is true, then isn't it possible to use a method that expects type T on an object of type A? Also, is my assumption that any method expecting a superclass object (e.g. T) will work on all sub-classes (A and A's children)?

like

public class A implements T {}

public void method(T obj) { do stuff to obj}

A objA = new A();

method(objA);

OUTPUT: do stuff to objA // no crashing or runtime exceptions

Upvotes: 1

Views: 490

Answers (1)

supercat
supercat

Reputation: 81159

If MyClass implements MyInterface, then a reference to a MyClass, or any type derived from MyClass, is also a reference to that interface. When cast to the interface type, using any member of that interface will cause the corresponding MyClass member to be used on the instance of MyClass (or type derived from it). These facts mean that in most cases code which expects a MyInterface will work as expected when given a reference to a MyClass, but that is not always 100% true. Some interfaces include "optional" functionality which is implemented in some but not all implementing classes. For example, an immutable key-value mapping class might implement the Map interface but not support the put method. A method which expects to add values to a passed-in Map would fail if given an reference to an object which did not allow such functionality.

Upvotes: 2

Related Questions