Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public variable in an interface?

I was reading this , and noted the second point in the question:

An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class? I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.

I read the answers and none of them seems to clarify this point, except this:

For .Net,

Your answer to The second interviewer is also the answer to the first one... Abstract classes can have implementation, AND state, interfaces cannot...

I think the answer to the interviewer was correct, as you cant have any variables inside the interface. I am a bit confused here. Can anybody clarify? My question is, why did the interviewer ask such a weird(?) question?

like image 837
Sharun Avatar asked May 16 '13 04:05

Sharun


People also ask

CAN interface have public variables?

interface variables are public, static, and final by definition; we're not allowed to change their visibility.

Why variables in interface are public?

To be able to access by all the implementing classes, interface variables are public.

What type of variable can be defined in an interface public?

4. What type of variable can be defined in an interface? Explanation: variable defined in an interface is implicitly final and static. They are usually written in capital letters.

Can we declare a variable in interface?

You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type.


1 Answers

All interface members are implicitly public, that is why you can't have public with properties or method in the interface.

interface C# - MSDN

Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.

For your question:

I think the answer to the interviewer was correct, as you cant have any variables inside the interface.

No. You can define properties in the interface. Something like:

interface ITest
{
    int MyProperty { get; set; }
}

public class TestClass : ITest
{
    public int MyProperty
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
}

EDIT:

An another interviewer asked me what if you had a Public variable inside the interface, how would that be different than in Abstract Class?

Probably the interviewer was trying to see if you would say that all members in interface are public by default, whereas in Abstract class you can have private, protected, public members etc.

like image 197
Habib Avatar answered Sep 25 '22 01:09

Habib