1

Why interface allow all classes?

For example I have the below code :

interface I1 { }
class C1 { }

public class Test{
     public static void main(String args[]){
        C1 o1 = new C1();
        I1 x = (I1)o1; //compiler compile its successfully but failed in run time
     }
}

I know why its failed in runtime because C1 class does not implements I1 interface. If Class C1 implements I1 then above code will work successfully.

Can someone explain why interface allow all class casting?

Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94

6 Answers6

5

There could be a

class C2 extends C1 implements I1 { ... }

An object of this class could be assigned to o1 and the cast would be perfectly OK also at runtime.

Henry
  • 42,982
  • 7
  • 68
  • 84
4

The issue is that the cast happens at runtime. This is because there might be a class C2 that derives from C1 and implements I1. So the object might actually be castable to I1 at runtime, but in general you can't tell at compilation time (except for super trivial examples like the one provided).

Sorin
  • 11,863
  • 22
  • 26
3

It's because Interface can be implemented by more than one class. On the other hand class can inherit only from one class. In class case compiler can determine at compile time if cast can be accomplished, for interfaces compiler can't figure it out for 100%.

hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36
2

It's a bad idea. The point of using an interface is to implement it like this:

    class C2 extends C1 implements I1 {
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
2

When you are casting, you are actually telling the compiler that "please compile this piece of code, i am sure, this is of correct type".

This is not a property of interface, you can write

C1 o1 = new C1();
Integer i = (Integer) o1;
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
1

Since C1 is not implementing I1, there is NO compromise between those 2, that is the reason of the error.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97