Reputation: 3082
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?
Upvotes: 5
Views: 4306
Reputation: 223247
All interface members are implicitly public, that is why you can't have public
with properties or method in the interface.
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.
Upvotes: 8
Reputation: 15148
Just to add to Habib's answer, everything in an interface is public, because really it wouldn't make any sense for something to be private, since there can't be any implementation in it, the private member would never be used, it can't be used since there is nothing to use it.
I guess this is sort of a question where you need to elaborate on it a little bit more, it's not a bad question at all, I would say.
Upvotes: 0