Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is interface variable instantiation possible?

As far as I know, interfaces cannot be instantiated.

If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible?

Interface:

public interface IDynamicCode<out TCodeOut>
{        
    object DynamicClassInstance { get; set; }
    TCodeOut Execute(string value = "");
}

InCode:

var x = new IDynamicCode<string>[10];

Result:

Result

UPDATE:

It only happens when array declared. Not a single instance.

like image 990
AsValeO Avatar asked Jun 18 '15 11:06

AsValeO


People also ask

Can you instantiate variables in interface?

In an interface, you can't instantiate variables and create an object.

Why can't you instantiate an interface?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.

Is it possible to initialize a variable present in an interface in Java?

Interface variables are static because java interfaces cannot be instantiated on their own. The value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned.

Can we declare a variable in interface without initializing?

Declaring final variable without initializationIf you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't you will get a compilation error.


1 Answers

You're not instantiating an interface, but an array of that interface.

You can assign an instance of any class that implements IDynamicCode<string> to that array. Say you have public class Foo : IDynamicCode<string> { }, you can instantiate that and assign it to an element of that array:

var x = new IDynamicCode<string>[10];
x[5] = new Foo();

Instantiating the interface would not compile:

var bar = new IDynamicCode<string>();
like image 80
CodeCaster Avatar answered Oct 27 '22 01:10

CodeCaster