Object-oriented in Groovy and Groovy object-oriented

Source: Internet
Author: User

Object-oriented in Groovy and Groovy object-oriented

As mentioned above, groovy supports scripts and classes. The previous section briefly describes the relationship between scripts and classes. This section mainly introduces the knowledge of classes in groovy, that is, object-oriented knowledge.

1. Type 1.1 Original Type

The original data types supported in groovy are the same as those in java, namely boolean, char, short, int, long, float, and double.

1.2 Categories

Classes in groovy are similar to those in java, but the following are unique to groovy:

  • publicModified fields are automatically converted to attribute variables, which can avoid many redundant get and set methods.
  • If the attribute or method does not have the access permission modifier, the default value is public, while the default value is proteced in java.
  • The class name does not need to be the same as the file name.
  • Multiple level-1 classes can be defined in a file. If no class is defined, the groovy file is considered as a script file.
1.2.1 common class

The common classes of groovy are similar to those of java, and instances are obtained using the new keyword.

1.2.2 internal class

The internal class is similar. The following is an example:

class Outer2 {    private String privateStr = 'some string'    def startThread() {       new Thread(new Inner2()).start()    }    class Inner2 implements Runnable {        void run() {            println "${privateStr}."        }    }}
1.2.3 abstract class

Abstract classes are similar to java:

abstract class Abstract {             String name    abstract def abstractMethod()     def concreteMethod() {        println 'concrete'    }}
1.3 Interface

The interfaces of groovy are similar to those of java, and interfaces inherited from interfaces are supported.

1.4 Constructor

Groovy constructor is slightly different from java. groovy constructor supportsLocation parametersAndNaming Parameters.

1.4.1 location parameter Construction Method

Location construction parameters are similar to the common construction methods in java. Parameters at different locations have different meanings. As follows:

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]        

When calling the constructor, groovy has two additional methods. Because the location is fixed, even ifPersonConstructor person3 = ['Marie', 3]Groovy can also initialize it for you internally.

1.4.2 construction of named Parameters

You do not need to define the name parameter constructor. When a class does not have a constructor, a name parameter constructor is used by default.

class PersonWOConstructor {                                      String name    Integer age}def person4 = new PersonWOConstructor()                      def person5 = new PersonWOConstructor(name: 'Marie')         def person6 = new PersonWOConstructor(age: 1)                def person7 = new PersonWOConstructor(name: 'Marie', age: 2) 
1.5 Method

The method for defining groovy is also very simple, and keywords can be used.defOr return value. All methods in groovy have returned values.returnStatement. groovy calculates the last statement in the method and returns the result.

The following are four different methods:

def someMethod() { 'method called' }                           String anotherMethod() { 'another method called' }             def thirdMethod(param1) { "$param1 passed" }                   static String fourthMethod(String param1) { "$param1 passed" }
1.5.1 method naming Parameters

To use a named parameter in a custom method, you must use Map as the unique parameter, as shown below:

def foo(Map args) { "${args.name}: ${args.age}" }foo(name: 'Marie', age: 1)
1.5.2 default parameters of the Method

The groovy method supports default parameters. In this way, the parameters become optional. When the parameters are not filled in, the default parameters are used:

def foo(Map args) { "${args.name}: ${args.age}" }foo(name: 'Marie', age: 1)
1.5.3 variable length parameter of the Method

This also exists in java. For example:

def foo(Map args) { "${args.name}: ${args.age}" }foo(name: 'Marie', age: 1)
1.6 annotations

The annotation in groovy is similar to that in java, but it has some more features than java. The following is a brief introduction.

1.6.1 annotation closure Parameters

In groovy, an interesting language feature is that it can be used.ClosureThe parameter value of the annotation. Under what circumstances is this annotation generally used? For example, in some cases, the software depends on the operating environment and operating system, and the performance varies with different environments or systems. Take a look at this example:

class Tasks {    Set result = []    void alwaysExecuted() {        result << 1    }    @OnlyIf({ jdk>=6 })    void supportedOnlyInJDK6() {        result << 'JDK 6'    }    @OnlyIf({ jdk>=7 && windows })    void requiresJDK7AndWindows() {        result << 'JDK 7 Windows'    }}

The Tasks class is used to completealwaysExecuted,supportedOnlyInJDK6,requiresJDK7AndWindowsThese three tasks have different requirements on the environment and system.@OnlyIfEnvironment and system requirements.

@Retention(RetentionPolicy.RUNTIME)@interface OnlyIf {    Class value()                    }

In groovy, if you need to make the annotation accept the closure, you only need to define a value of the Class type as above. In this way, OnlyIf can accept the closure as its value.

Then write the processing class:

class Runner {    static <T> T run(Class<T> taskClass) {        def tasks = taskClass.newInstance()                                                 def params = [jdk:6, windows: false]                                                tasks.class.declaredMethods.each { m ->                                                 if (Modifier.isPublic(m.modifiers) && m.parameterTypes.length == 0) {                   def onlyIf = m.getAnnotation(OnlyIf)                                                if (onlyIf) {                    Closure cl = onlyIf.value().newInstance(tasks,tasks)                                cl.delegate = params                                                                if (cl()) {                                                                             m.invoke(tasks)                                                                 }                } else {                    m.invoke(tasks)                                                                 }            }        }        tasks                                                                           }}

Similar to java, it obtains the method of the Task object through reflection and obtains its OnlyIf annotation. If the result is obtained successfully, it extracts the closure of OnlyIf for calling.

2 Traits)

Trait is a unique object-oriented syntax feature in groovy. It has the following features:

  • Behavior Composition
  • Runtime interface implementation
  • Behavior Overloading
  • Check and compile compatibility with static types

Trait can be viewed as an interface with method implementation and status.traitKeyword definition:

trait FlyingAbility {                                   String fly() { "I'm flying!" }          }

The above defines a special proof of flight capability, which is used in the same way as interfaces.implementsKeywords:

class Bird implements FlyingAbility {}          def b = new Bird()                              assert b.fly() == "I'm flying!" 

This seems like inheritance, but it is different. trait only embeds its method and status into the implementation class, without the parent-child relationship in inheritance.

Some syntax features in trait:

  • Trait supports defining abstract methods. Its implementation class must implement this abstract method.
  • A private method can be defined in trait, and its implementation class cannot be accessed.
  • The this keyword in trait indicates its implementation class.
  • Trait can implement interfaces.
  • You can define attributes in trait. This attribute is automatically attached to the class that implements this trait.
  • Trait can define private fields due to storage-related status.
  • Trait can define public fields, but to avoidDiamond ProblemsAnd the retrieval method is different, as follows:
trait Named {    public String name                      }class Person implements Named {}            def p = new Person()                        p.Named__name = 'Bob'   
  • The first class can implement multiple trait.
  • The implementation class can override the default method in trait.
  • Trait can inherit from another trait and use the keyword extends. If you want to inherit multiple trait, use the implements keyword.
  • You can dynamically implement trais at runtime and use the keyword.

The above briefly introduces the Object-Oriented Knowledge in groovy. For more information, see the official documentation.

  • Object orientation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.