In the previous article, we learned how to build a groovy development environment to prepare for our groovy journey, and do not know if you are ready? Let's take a look at the similarities and differences between groovy and what we know about Java.
Groovy is lightweight Java, which differs from Java in six main points, which we'll explain in one step.
One: Both the return statement and the semicolon are optional.
Groovy codedef int Add (A, b) { A + b}println Add (1, 2)
Console output:
3
Two: Methods and classes are public by default.
Three:?. The call is dispatched only if the object reference is not empty.
Groovy codedef foo (str) { str?. Reverse ()}println foo (' evil ') println foo (null)
Console output:
Live
Null
Four: can make the appliance name parameter initialization JavaBean.
Package com.test.bean/** * JavaBean */class Robot { def weight, height, width def access (weight, height, width) { C2/>println "Weight: $weight, Height: $height, Width: $width" }}
Here is the test class:
Package Com.testimport com.test.bean.robot/** * Groovy Test */class groovytest {public static void Main (string[] args { Robot Robot = new Robot (weight:30, Height: ' height ', width:10) robot.access (+, robot.height, +);} }
Console output:
weight:100, Height:height, width:300
Five: Groovy does not force us to capture exceptions that we do not care about, and exceptions can be passed on to the caller for processing.
Class Exceptiontest { def static openFile (fileName) { //can not be concerned with the exception thrown by the following code, which is given to the caller to handle the new FileInputStream ( fileName) }}
Here is the test class:
Class Groovytest {public static void Main (string[] args) { //caller handles exception try { exceptiontest.openfile (" Test.txt ") } catch (FileNotFoundException e) { println e }} }
Console output:
Java.io.FileNotFoundException:test.txt (the system cannot find the file specified.) )
Six: You can use this in a static method to refer to a class object.
Groovy Learning Notes (ii)