Click here to Skip to main content
15,918,049 members
Please Sign up or sign in to vote.
4.00/5 (4 votes)
See more:
The following code compile in java and C# and I can't understand why:
C#
public interface A
{
}

public class B
{
}

public class C
{
    private void foo(A a)
    {
        B b = (B)a;
    }
}


A is not related to B in any way. If I change A to be a class instead of an interface the code will not compile. Why does declaring A as an interface change that?
Posted
Updated 16-Dec-10 4:35am
v2
Comments
Toli Cuturicu 16-Dec-10 10:33am    
Interview or homework? Either way, CodeProject is the wrong place to ask this!
RanCohen 16-Dec-10 14:18pm    
None of the above - I got a ClassCastException in my program and couldn't figure out why the compiler didn't block me in the first place...
And why is CodeProject the wrong place to ask this?
Toli Cuturicu 18-Dec-10 17:46pm    
The CodeProject members ususally do not like to answer what seems to be homework or interview questions.

1 solution

There isn't an error at compile time because a derived class of B can also have implemented interface A. The compiler doesn't check that but if you would test it and pass a class D for example that implements A but is not a descendant of B, you would get an error.

Good luck!
 
Share this answer
 
Comments
RanCohen 16-Dec-10 14:18pm    
That makes sense, thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900