Here is the scenario: I have an interface A, 100 classes B0 … B99 that implement only A and 50 classes C0, C2 … C98 that extend B0, B2 … B98.
The B classes work with a MySQL database, doing various stuff on the tables.
The C classes add extra logic to B classes (validations, privileges etc).
The B classes are generated by a tool, while the C classes are written by a coder.
A client application will use the B classes and will not have access to C classes. When a method is called for a B object, the client will serialise the object and send it to a server application, along with the method name that is to be called.
The server will receive the B object and cast it as an A. However, the server would like to execute the method that was overridden in the C class if such a class exists, and the method from B otherwise. Normal behaviour would only execute the method from B.
How would the server be able to do that without having a huge SWITCH statement that would cast the received object to a C?
EDIT: I am new to java and did not know what reflection could do. With a little help from google (this and this) I solved my problem. I can use dynamic casting for what I want to achieve. Thanks to everybody.
Well you have an object of runtime type B, and you are asking to call it as if it were an object of type C. This isn’t really how inheritance works; you cannot downcast to C unless it was originally created as a C, because in general, it doesn’t have all the fields of C.
I am guessing your C classes do not add any additional fields to a B (if they did, your question wouldn’t make sense). Since they don’t add any additional fields, then I can see how it would make sense to treat them as a C, but there isn’t a really good way to do it. I would say: