使用受保护的方法注入类实例

I have two classes: "User" and "Room". Class "Room" uses the class "User" a lot, so when I declare class "Room", I pass class "User" instance as one of its parameters.

The problem is that class "User" properties/methods are protected, so "Room" cannot use the injected "User" instance.

Then I have to make class "Room" extend class "User" so it has access to the protected stuff.

Since "Room" will inherit all the stuff from "User" which will never be used, the logic says this practice is wrong? Any other way to do it?

You should really not make "Room" extend "User". While that would possibly work it would break the 3rd rule of the SOLID principles which basically means the sub class should mainly behave just like the parent class.

So what you can do:

  1. If you have access to the class itself (e.g. it is not part of 3rd party code like a library) you can just modify it and write getters and change the visibility of methods. This is perfectly legal if it is your code. Dependencies change over time so sometimes it is necessary to do just that.

  2. Extend "User" with your own User class and put the getters in it or overwrite the methods. Of course in "Room" you must use your new User class instead.

Add the public methods to class User, thats could be used by class Room and create Class Interface with that all alowed public methods. The public methods should call private methods, instead of call private methods directly from the parent class.