Groovy 特征


本文整理自网络,侵删。

特征是语言的结构构造,允许 -

  • 行为的组成。
  • 接口的运行时实现。
  • 与静态类型检查/编译的兼容性

它们可以被看作是承载默认实现和状态的接口。使用trait关键字定义 trait。

下面给出了一个特征的例子:

trait Marks {
   void DisplayMarks() {
      println("Display Marks");
   } 
}

然后可以使用 implement 关键字以类似于接口的方式实现 trait。

class Example {
   static void main(String[] args) {
      Student st = new Student();
      st.StudentID = 1;
      st.Marks1 = 10; 
      println(st.DisplayMarks());
   } 
} 

trait Marks { 
   void DisplayMarks() {
      println("Display Marks");
   } 
} 

class Student implements Marks { 
   int StudentID
   int Marks1;
}

实现接口

Traits 可以实现接口,在这种情况下,使用 interface 关键字声明接口。

下面给出了实现接口的特征的示例。在以下示例中,可以注意以下要点。

  • 接口 Total 使用方法 DisplayTotal 定义。

  • 特征 Marks 实现了 Total 接口,因此需要为 DisplayTotal 方法提供一个实现。

class Example {
   static void main(String[] args) {
      Student st = new Student();
      st.StudentID = 1;
      st.Marks1 = 10;
		
      println(st.DisplayMarks());
      println(st.DisplayTotal());
   } 
} 

interface Total {
   void DisplayTotal() 
} 

trait Marks implements Total {
   void DisplayMarks() {
      println("Display Marks");
   }
	
   void DisplayTotal() {
      println("Display Total"); 
   } 
} 

class Student implements Marks { 
   int StudentID
   int Marks1;  
} 

上述程序的输出将是 -

Display Marks 
Display Total

属性

特征可以定义属性。下面给出了具有属性的trait的示例。

阅读剩余部分

相关阅读 >>

Groovy 条件语句

Groovy xml

Groovy 文件io

Groovy 数据类型

Groovy 特征

Groovy 概述

Groovy 字符串

Groovy 列表

Groovy 单元测试

Groovy 范围

更多相关阅读请进入《Groovy》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...