Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 classes implement same interface, duplicated code

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.

like image 297
loyalflow Avatar asked Feb 07 '14 17:02

loyalflow


People also ask

How can interface be used in multiple classes?

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.

Can we implement an interface in two classes?

Yes an interface can be implemented by multiple classes.

What happens when two classes implement the same interface?

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.


2 Answers

Yes. You can.

public abstract class BaseUser : IUser
{

}

public class User : BaseUser 
{

}

public class AdminUser : BaseUser
{

}
like image 149
i3arnon Avatar answered Nov 01 '22 00:11

i3arnon


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 { } 
like image 42
JaredPar Avatar answered Oct 31 '22 23:10

JaredPar