Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an Interface contain a variable? [duplicate]

Possible Duplicate:
Why can't C# interfaces contain fields?

Hi all,

Jon Skeet has answered to a question that Using a property is backed by a variable.

But properties in Interfaces are allowed in C#. Does that mean the interfaces in C# can contain a variable and how would the variable backed by the property will be handled?

Thanks in advance.

like image 437
Sandeep Avatar asked Apr 18 '11 04:04

Sandeep


People also ask

Can an interface contain variables?

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.

What variables are allowed inside an interface?

The interface contains the static final variables. The variables defined in an interface can not be modified by the class that implements the interface, but it may use as it defined in the interface. 🔔 The variable in an interface is public, static, and final by default.

Can interface has variable Java?

In Java, an interface is an abstract type that contains a collection of methods and constant variables.

Should interface have variables?

You shouldn't put any variables inside Interfaces. Because interfaces define contracts which can be implemented in various ways. The value of a variable is implementation. We certainly can when we know all the classes implementing the interface have some constant variables(Field names for instance).


1 Answers

No. An interface cannot contain a field.

An interface can declare a Property, but it doesn't provide any implementation of it, so there's no backing field. It's only when a class implements an interface that a backing field (or automatic property) is needed.

like image 65
Andrew Cooper Avatar answered Sep 29 '22 02:09

Andrew Cooper