I have an interface:
public interface IUser
{
}
And then 2 classes that implement this interface:
public class User : IUser
{
}
public class AdminUser : IUser
{
}
Now the problem I see is that there is duplicate code between User and AdminUser when implementing a method in the interface.
Can I introduce an abstract class that would implement the common code between User and AdminUser somehow?
I don't want AdminUser to inherit from User.
An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.
Yes an interface can be implemented by multiple classes.
A class can implement multiple interfaces and many classes can implement the same interface. A class can implement multiple interfaces and many classes can implement the same interface. Final method can't be overridden. Thus, an abstract function can't be final.
Yes. You can.
public abstract class BaseUser : IUser
{
}
public class User : BaseUser
{
}
public class AdminUser : BaseUser
{
}
Sounds like you should introduce a UserBase
class that both User
and AdminUser
could inherit from that has the shared code
class UserBase : IUser {
// Shared Code
}
class User : UserBase { }
class AdminUser : UserBase { }
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