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
  • 相关阅读:
    codeforces 466D
    codeforces 360B
    codeforces 383D
    codeforces 679B
    codeforces 571B
    codeforces 494B
    CodeForces 660D Number of Parallelograms(n个点所能组成的最多平行四边形数量)
    算法竞赛模板 最短路
    算法竞赛模板 string中substr函数的运用
    HDOJ 1269 迷宫城堡(tarjan模板题)
  • 原文地址:https://www.cnblogs.com/jsersudo/p/10154726.html
Copyright © 2011-2022 走看看