Saurabh Agarwal
Saurabh Agarwal

Reputation: 323

Object Class Inheritance with Interfaces

Can Object class reference variable refer to the reference holed by some Interface reference variable. As we know Interface can't extend any class. So default inheritance of Object class will work with such scenario or not. Obviously answer is Yes but what's the logic behind this.?

    public interface ToTest {

    }

    public class ToTestImpl implements ToTest{

    }

    public class ToTestClass {

        public static void main(String args[]){
            ToTest test = new ToTestImpl();
            Object o = test;
            System.out.println(o);
        }
    }

Upvotes: 1

Views: 62

Answers (2)

NPE
NPE

Reputation: 500357

The logic is that every Java class is a descendant of Object, irrespective of any interfaces it implements. Thus any reference can be upcast to Object.

The mechanics that apply to your case are spelled out in §5.5.1. Reference Type Casting and §5.5.3. Checked Casts at Run Time of the JLS. The details are a bit complicated, since there's both a compile-time and a run-time components. The relevant quote is:

Here is the algorithm to check whether the run-time type R of an object is assignment compatible with the type T...

If R is an interface:

  • If T is a class type, then T must be Object (§4.3.2), or a run-time exception is thrown.

Upvotes: 2

Ankit
Ankit

Reputation: 6622

yes, it would work. Because, compiler knows interfaces are not meant to be instantiate. So even if you assign an interface reference to Object, it is obvious that any implementation of that interface will come from Object's hierarchy.

Upvotes: 0

Related Questions