My question is regarding Type Casting in different interfaces
Suppose I have an interface
public interface I
{
void method();
}
A class implementing it
public class C : I
{
public void method()
{
}
}
I have another interface
public interface I1
{
void method1();
}
Now if i do something like this
C c1 = new C();
((I1)c1).method1();
It throws a run time exception rather than a compile time error
A compile time error is an error that is detected by the compiler. Common causes for compile time errors include: Syntax errors such as missing semi-colon or use of a reserved keyword (such as 'class'). When you try and access a variable that is not in scope.
The Errors that occur due to incorrect syntax are known as compile-time errors or sometimes also referred to as syntax errors in java. Examples of compile-time errors include: missing parenthesis, missing a semicolon, utilizing undeclared variables, etc.
Compile-time checking occurs during the compile time. Compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler.
Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps programmers debugging the source code.
Because C
is not marked sealed
I could potentially do this
public D : C, I1
{
public void method1()
{
}
}
Which would make the following code perfectly legal.
C c1 = new D();
((I1)c1).method1();
If C
is marked sealed
you should get a compile time error as there can't exist a more derived class that could be implementing the interface.
public sealed class C : I
{
public void method()
{
}
}
//You should now get the compile time error "Cannot convert type 'SandboxConsole.C' to 'SandboxConsole.I1'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With