zoukankan      html  css  js  c++  java
  • groovy类、构造函数、方法

    数据类型:groovy支持Java语言规范定义的数据类型
    类:与Java类的主要区别
    1、没有可见修饰符的类或者方法是自动公开的
    2、类不需要与源文件定义相同名称,但是默认规定定义一样
    3、一个源文件包含一个或者多个类,但是如果文件包含不再类中的任何代码将视为脚本
    4、脚本只是具有一些特殊约定的类
    5、不要在脚本中定义与脚本源文件相同名称的类定义
    6、必须用abstract关键字修饰抽象方法和类
    7、可以使用as运算符使对象的实例在运行时实现接口

    /**
     * Created by Jxy on 2018/12/21 7:43
     * 三种构造函数的使用
     * Groovy方法、参数
     */
    class PersonConstructor {
        String name
        Integer age
    
        PersonConstructor(name, age) {
            this.name = name
            this.age = age
        }
    }
    
    def person1 = new PersonConstructor('Marie', 1)
    def person2 = ['Marie', 2] as PersonConstructor
    PersonConstructor person3 = ['Marie', 3]
    /*
    方法基本的定义
     */
    def someMethod() { 'method called' }//声明没有返回值类型并且没有参数的方法
    String anotherMethod() { 'another method called' }//具有显式返回类型且无参数的方法
    def thirdMethod(param1) { "$param1 passed" }//没有定义类型的参数的方法
    static String fourthMethod(String param1) { "$param1 passed" }//带String参数的静态方法
    /*
    方法的命名参数
     */
    def foo(Map args) { "${args.name}: ${args.age}" }
    def string = foo(name: 'Marie', age: 1)
    println(string)//Marie: 1
    /*
    方法参数混合命名和位置参数
    Mixing named and positional parameters
    map必须放在参数第一个位置不然会报异常:groovy.lang.MissingMethodException
     */
    def foo(Map args, Integer number) { "${args.name}: ${args.age}, and the number is ${number}" }
    foo(name: 'Marie', age: 1, 23)
    foo(23, name: 'Marie', age: 1)
    
    /*
    如果map没有在第一个参数位置则应该使用显示map参数替换命名参数
     */
    def foo(Integer number, Map args) { "${args.name}: ${args.age}, and the number is ${number}" }
    foo(23, [name: 'Marie', age: 1])
    
    /*
    默认参数
     */
    def foo(String par1, Integer par2 = 1) { [name: par1, age: par2] }
    assert foo('Marie').age == 1
    /*
    可变参数
    可变参数与重载
     */
    def foo(Object... args) { 1 }
    def foo(Object x) { 2 }
    assert foo() == 1
    assert foo(1) == 2
    assert foo(1, 2) == 1
  • 相关阅读:
    特征工程系列:GBDT特征构造以及聚类特征构造
    SQL语句优化,数据分析师必须掌握!
    Win8下修改任務欄的資源管理器默認打開位置
    eclipse升级,导入旧版eclipse的插件[转]
    内网Linux对公网开启SSH
    windows上传文件到linux
    Chrome每次打開都要打開123.sogou.com
    maven下载的jar文件出现invalid LOC header (bad signature)
    requesting java ast from selection
    JConsole connection failed
  • 原文地址:https://www.cnblogs.com/jsersudo/p/10154726.html
Copyright © 2011-2022 走看看