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?
interface variables are public, static, and final by definition; we're not allowed to change their visibility.
To be able to access by all the implementing classes, interface variables are 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.
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.
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.
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