开发者

When And Where To Use Object Instance and Class name in Grails?

I have been confused, by seeing the code(actually an test code) :

def user = new User(userId:'anto',password:'xxxx')
        user.addToPosts(new Post(content:"First"))
        def foundUser = User.get(user.id)

In the above code, I have created a object for User class and named as user. If I replace the line :

def foundUser = User.get(user.id)

To something like this,

def foundUser = user.get(user.id)

I.e I have changed from class name User t开发者_JS百科o user object name. And when I run the test, it doesn't throw me any error.

But when I change this line to :

user.addToPosts(new Post(content:"First"))

To something like,

User.addToPosts(new Post(content:"First"))

I'm getting an error! So what happens behind the scenes? For which scenarios I have to use the object name and for which scenarios class name? And Why?

Thanks in Advance.


get() is a static method on the User class since it has nothing to do with an individual instance - it returns an instance. So you typically call it on the class, but you can also call static methods on instances. If you do this in Java your IDE will warn you that it will work but shouldn't be done, but I doubt any IDE does this for Groovy (yet).

addToPosts() is an instance method since it must be called on an instance to add a Post to a User instance's posts collection. You can't call it on the class since that makes no sense - the class doesn't have a posts collection to add to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜