Groovy 面向对象
面向对象阅读笔记。
1.类型
1.1.基础类型
- 整型:
byte
(8bit),short
(16bit),int
(32bit),long
(64bit) - 浮点型:
float
(32bit),double
(64bit) - boolean
- char(16bit): 可作为数字类型使用,代表UTF-16编码
Groovy使用和Java相同的装箱和拆箱。对应如下:
基础类型 | 包装类型 |
---|---|
boolean | Boolean |
char | Character |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
1.2类
Groovy与Java的区别:
没有可见性修饰符的类或方法默认为公共修饰符
没有可见性修饰符的字段会转换为属性,属性没有显式的getter和setter方法。
类的包名可以和类文件的路径名不相同
一个源文件可以包含一个或多个类。但如果一个源文件中出现不在类中的代码时将被是为脚本
脚本是具有一些特殊约定的类,它的名称和原文件相同,因此不要在脚本中定义与源文件同名的类
class Person {
String name
Integer age
def increaseAge(Integer years) {
this.age += years
}
}
1.2.1普通类
普通类是指顶层和具体的类。普通类只能是公开的
1.2.2内部类
内部类可以访问外部类的成员,即使是私有的。
外部类以外的类不允许访问内部类。
class Outer {
private String privateStr
def callInnerMethod() {
new Inner().methodA()
}
class Inner {
def methodA() {
println "${privateStr}."
}
}
}
存疑:
原文中说
Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes
翻译是:内部类在另一个类中定义。封闭类可以照常使用内部类。另一方面,内部类可以访问其封闭类的成员,即使它们是私有的。封闭类以外的类不允许访问内部类。
但在如下代码中却可以访问内部类:
class Demo {
public static void main(String[] args) {
def demo = new Demo()
demo.run()
}
public void run() {
def list = [new Outer.Inner(), new Outer.Inner(), new Outer.Inner(), new Outer.Inner()]
list.each { it -> println it.a }
}
}
从Groovy3.0开始,支持用于非静态内部类实例语法:
class Computer {
class Cpu {
int coreNumber
Cpu(int coreNumber) {
this.coreNumber = coreNumber
}
}
}
assert 4 == new Computer().new Cpu(4).coreNumber