开发者

Changing class of object to subclass (& general questions on inheritance)

开发者 https://www.devze.com 2023-04-07 16:00 出处:网络
Suppose I have a class clubMember and a class user. Only club members can be users, users have login data additional to other club member vars, and club members’ characteristics influence what rights

Suppose I have a class clubMember and a class user. Only club members can be users, users have login data additional to other club member vars, and club members’ characteristics influence what rights as users they have, so user extends clubMember.

Now suppose a club member wants to use the grails servlet I am currently programming. Creating a new user instance would lead to a double entry, plus I would lose all the links existing between the previous member and other classes. So perhaps converting the type of the clubMember to user would be the best way to proceed? If so, how could that be done (in Groovy)?

Or, could you recommend me an implemention method other than subclasses? Ideally, requests such as “list all members” should also return users, is this even the case with subclasses? (Edit: It is the case in开发者_开发知识库 my grails app)

Related: Java: Creating a subclass object from a parent object, Is it ever valid to convert an object from a base class to a subclass


If you want one value of a certain type to become a new value of a different type, then you have in Groovy basically two ways:

  1. asType: In for example "foo as Bar" Groovy will convert the expression to "foo.asType(Bar.class)", which means you can add an asType method to the class of foo to do the conversion for you. In your case you would add asType to User and let it handle ClubMember.
  2. explicit or implicit cast: In "(Bar) collection" Groovy will look for a constructor in Bar that can take a fitting number of arguments for the collection and will then create a new Bar object out of it. Actually it is not limited to collections, an array will do as well. Anyway... In your example you could add a constructor that takes ClubMember to User and then cast the collection containing the member you want to convert. On a side node... if you assign the collection to a Bar typed variable, this conversion will also happen (implicit cast).

If you want the conversion method (I am so free and call the constructor a conversion method as well) not in the class, you can still use a category for the asType version or runtime meta programming to add an asType method as you need or a constructor as you need.

But what Tim suggested in his comment, to have ClubMember as member of User seems really to be the most easy version

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号