趁有空,再了解一下GROOVY中关于类的通例

简单的,浅浅的看一下。

想起了RUBY里覆盖类的方法。。。

在GROOVY里也同样提到了,比如TOSTRING。。。

(其实,在我以前的经验中,从未用过这些东东。。:))

这样用了PACKAGE,显得正规点。。

Song.groovy

复制代码
package org.acme.groovy

class Song {

    def name
    def artist
    def genre
    
    String toString(){
        "${name}, ${artist}, ${genre}"
    }
    
    def getGenre(){
        genre?.toUpperCase()
    }

}
复制代码

SongExample.groovy

复制代码
package org.thirdparty.lib
import org.acme.groovy.Song

class SongExample {


    static main(args) {
        def sng = new Song(name:"Le Freak",
            artist:"Chic", genre:"Disco")
        def sng2 = new Song(name: "Kung Fu Fighting", genre: "Disco")
        def sng3 = new Song()
        sng3.name = "Funkytown"
        sng3.artist = "Lipps Inc."
        sng3.setGenre("Disco")
        
        assert sng3.genre == "Disco".toUpperCase()
        
        println sng2.artist?.toUpperCase()
        
        println sng3.getArtist()
        println sng.name
        println sng.getGenre()
        println sng3.toString()
        
        
    
    }

}
复制代码

输出: