diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9d1c634 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +notes.txt +test.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000..db2d3f8 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +## Install Groovy on Windows + +1. Go here http://groovy-lang.org/download.html + +2. Click Windows Installer and click next a bunch of times until it is installed. + +--- + +## Install Groovy on Ubuntu 20.04 + +### Install Open JDK +Install OpenJDK 14 version +`sudo apt install openjdk-14-jdk*` +`sudo apt install openjdk-14-jre*` + +edit your .bashrc file +`vi ~/.bashrc` +add the following 2 lines to the end of the file +``` +export JAVA_HOME=/usr/lib/jvm/java-14-openjdk-amd64/ +export PATH=$JAVA_HOME/bin:$PATH +``` + +Source .bashrc so changes take effect +`source ~/.bashrc` + +### Install Groovy 3.x +`sudo snap install groovy --classic` + +--- + +## Install Groovy on Mac +1. Update Java to at least Java 7 in the System Preferences Java Control Panel + +2. Type in Terminal /usr/libexec/java_home -V +to get something like +1.7.0_55, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home + +3. Type in terminal export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_55, x86_64` + +4. Type in terminal java -version and make sure you have at least Java 7 + +5. Install HomeBrew at http://brew.sh/ + +6. Type in terminal brew install groovy + +--- + +### Update Atom for Groovy +In Atom Open Command Palette -> Install Packages Themes -> Type language-groovy and install + +--- + +## Run Groovy code +Groovy files have the extension `.groovy`. You can run a groovy file at the terminal with: +`groovy myfile.groovy` diff --git a/lesson_01_hello-world/hello_world.groovy b/lesson_01_hello-world/hello_world.groovy new file mode 100644 index 0000000..678a853 --- /dev/null +++ b/lesson_01_hello-world/hello_world.groovy @@ -0,0 +1,5 @@ +class GroovyHelloWorld{ + static void main(String[] arg){ + println("Hello World!!!"); + } +} diff --git a/lesson_02_math/math.groovy b/lesson_02_math/math.groovy new file mode 100644 index 0000000..4eb03a7 --- /dev/null +++ b/lesson_02_math/math.groovy @@ -0,0 +1,97 @@ +class GroovyMath{ + static void main(String[] arg){ + + // ---------- MATH ---------- + // Everything in Groovy is an object + // including numbers + + // def is used when you define a variable + // Variables start with a letter and can + // contain numbers and _ + // Variables are cynamically typed and can + // hold any value + + def age = "Dog"; + age = 40; + + // The basic integer math operators + println("\nBasic Math"); + println("5 + 4 = " + (5 + 4)); + println("5 - 4 = " + (5 - 4)); + println("5 * 4 = " + (5 * 4)); + println("5 / 4 = " + (5.intdiv(4))); + println("5 % 4 = " + (5 % 4)); + + // Floating point math operators + println("\nFloat Math"); + println("5.2 + 4.4 = " + (5.2.plus(4.4))); + println("5.2 - 4.4 = " + (5.2.minus(4.4))); + println("5.2 * 4.4 = " + (5.2.multiply(4.4))); + println("5.2 / 4.4 = " + (5.2 / 4.4)); + + // Order of operations + println("\nOrder of operations") + println("3 + 2 * 5 = " + (3 + 2 * 5)); + println("(3 + 2) * 5 = " + ((3 + 2) * 5)); + + // Increment and decrement + println("\nIncrement or decrement") + println("age++ = " + (age++)); + println("++age = " + (++age)); + println("age-- = " + (age--)); + println("--age = " + (--age)); + + // Largest values + println("\nLargest or smallest values") + println("Biggest Int " + Integer.MAX_VALUE); + println("Smallest Int " + Integer.MIN_VALUE); + + println("Biggest Float " + Float.MAX_VALUE); + println("Smallest Float " + Float.MIN_VALUE); + + println("Biggest Double " + Double.MAX_VALUE); + println("Smallest Double " + Double.MIN_VALUE); + + // Decimal Accuracy + println("\nDecimal accuracy example"); + println("1.1000000000000001111111111111111111111111111111111111 + 1.1000000000000001111111111111111111111111111111111111 " + + (1.1000000000000001111111111111111111111111111111111111 + 1.1000000000000001111111111111111111111111111111111111)); + + // Math Functions + println("\nMore advanced math functions") + def randNum = 2.0; + println("Math.abs(-2.45) = " + (Math.abs(-2.45))); + println("Math.round(2.45) = " + (Math.round(2.45))); + println("randNum.pow(3) = " + (randNum.pow(3))); + println("3.0.equals(2.0) = " + (3.0.equals(2.0))); + println("randNum.equals(Float.NaN) = " + (randNum.equals(Float.NaN))); + println("Math.sqrt(9) = " + (Math.sqrt(9))); + println("Math.cbrt(27) = " + (Math.cbrt(27))); + println("Math.ceil(2.45) = " + (Math.ceil(2.45))); + println("Math.floor(2.45) = " + (Math.floor(2.45))); + println("Math.min(2,3) = " + (Math.min(2,3))); + println("Math.max(2,3) = " + (Math.max(2,3))); + + // Number to the power of e + println("\nPower of e") + println("Math.log(2) = " + (Math.log(2))); + + // Base 10 logarithm + println("\nlog base 10") + println("Math.log10(2) = " + (Math.log10(2))); + + // Degrees and radians + println("\nConvert degrees to radians and vice versa") + println("Math.toDegrees(Math.PI) = " + (Math.toDegrees(Math.PI))); + println("Math.toRadians(90) = " + (Math.toRadians(90))); + + // sin, cos, tan, asin, acos, atan, sinh, cosh, tanh + println("\nTrig stuff") + println("Math.sin(0.5 * Math.PI) = " + (Math.sin(0.5 * Math.PI))); + + // Generate random value from 1 to 100 + println("\nRandon numbers") + println("Math.abs(new Random().nextInt() % 100) + 1 = " + (Math.abs(new Random().nextInt() % 100) + 1)); + + } +} diff --git a/lesson_03_strings/strings.groovy b/lesson_03_strings/strings.groovy new file mode 100644 index 0000000..2831a47 --- /dev/null +++ b/lesson_03_strings/strings.groovy @@ -0,0 +1,77 @@ +class GroovyStrings{ + static void main(String[] arg){ + // ---------- STRINGS ---------- + + def name = "Frank"; + + // A string surrounded by single quotes is taken literally + // but backslashed characters are recognized + println('I am ${name}\n'); + println("I am $name\n"); + println("I am ${name}\n"); + + // Triple quoted strings continue over many lines + def multString = '''I am + a string + that goes on + for many lines'''; + + println(multString); + + // You can access a string by index + println("3rd Index of Name " + name[3]); + println("Index of r " + name.indexOf('r')); + + // You can also get a slice + println("1st 3 Characters " + name[0..2]); + + // Get specific Characters + println("Every Other Character " + name[0,2,4]); + + // Get characters starting at index + println("Substring at 1 " + name.substring(1)); + + // Get characters at index up to another + println("Substring at 1 to 4 " + name.substring(1,4)); + + // Concatenate strings + println("My Name " + name); + println("My Name ".concat(name)); + + // Repeat a string + println("Repeat a string") + def repeatStr = "What I said is " * 2; + println(repeatStr); + + // Check for equality + println("Frank == Frank : " + ('Frank'.equals('Frank'))); + println("Frank == frank : " + ('Frank'.equalsIgnoreCase('frank'))); + + // Get length of string + println("Size or length " + repeatStr.length()); + + // Remove first occurance + println(repeatStr - "What"); + + // Split the string + println(repeatStr.split(' ')); + println(repeatStr.toList()); + println(repeatStr.split('a')) + + // Replace all strings + println(repeatStr.replaceAll('I', 'she')); + + // Uppercase and lowercase + println("Uppercase " + name.toUpperCase()); + println("Lowercase " + name.toLowerCase()); + println("Capitalize " + name.toLowerCase().capitalize()) + // println("Capitalize " + capitalizeAll(repeatStr)); + + // <=> returns -1 if 1st string is before 2nd + // 1 if the opposite and 0 if equal + println("Ant <=> Banana " + ('Ant' <=> 'Banana')); + println("Banana <=> Ant " + ('Banana' <=> 'Ant')); + println("Ant <=> Ant " + ('Ant' <=> 'Ant')); + + } +} diff --git a/lesson_04_output/output.groovy b/lesson_04_output/output.groovy new file mode 100644 index 0000000..8ce7839 --- /dev/null +++ b/lesson_04_output/output.groovy @@ -0,0 +1,17 @@ +class GroovyOutput{ + static void main(String[] arg){ + // ---------- OUTPUT ---------- + // With double quotes we can insert variables + def randString = "Random"; + println("A $randString string"); + + // You can do the same thing with printf + printf("A %s string \n", randString); + + // Use multiple values + printf("%-10s %d %.2f %10s \n", ['Stuff', 10, 1.234, 'Random']); + + // Single quotes are string literals + println('A $randString string'); + } +} diff --git a/lesson_05_input/input.groovy b/lesson_05_input/input.groovy new file mode 100644 index 0000000..4489167 --- /dev/null +++ b/lesson_05_input/input.groovy @@ -0,0 +1,19 @@ +class GroovyInput{ + static void main(String[] arg){ + // ---------- INPUT ---------- + print("Whats your name "); + def fName = System.console().readLine(); + println("Hello " + fName); + + // You must cast to the right value + // toInteger, toDouble + print("Enter a number "); + def num1 = System.console().readLine().toDouble(); + + print("Enter another number "); + def num2 = System.console().readLine().toDouble(); + + printf("%.2f + %.2f = %.2f \n", [num1, num2, (num1 + num2)]); + + } +} diff --git a/lesson_06_lists/lists.groovy b/lesson_06_lists/lists.groovy new file mode 100644 index 0000000..a956ab9 --- /dev/null +++ b/lesson_06_lists/lists.groovy @@ -0,0 +1,68 @@ +class GroovyLists{ + static void main(String[] arg){ + // ---------- LISTS ---------- + // Lists hold a list of objects with an index + + def primes = [2,3,5,7,11,13]; + + println("My list is $primes") + + // Get a value at an index + println("2nd Prime " + primes[1]); + println("3rd Prime " + primes.get(2)); + + // They can hold anything + def employee = ['Derek', 40, 6.25, [1,2,3]]; + + println("2nd Number " + employee[3][1]); + + // Get the length + println("Length " + primes.size()); + + // Add an index + primes.add(17); + + // Append to the right + primes<<19; + primes.add(23); + + // Concatenate 2 Lists + def primes_cat = primes + [29,31] + println("Primes cat is $primes_cat") + primes + [29,31]; + // println("Primes after adding [29,31] is '$primes'") + + + // Remove the last item + primes - [31]; + + // Check if empty + println("Is empty " + primes.isEmpty()); + + // Get 1st 3 + println("1st 3 " + primes[0..2]); + + println(primes); + + // Get matches + println("Matches " + primes.intersect([2,3,7, 122])); + + // Reverse + println("Reverse " + primes.reverse()); + + // Sorted + println("Sorted " + primes.sort()); + + // Pop last item + println("First " + primes.pop()); + println("Primes after first item popped $primes") + + //Remove last item + println("Last " + primes.removeLast()) + println("Primes after last element removed $primes") + + // Push an element to the front of the list + primes.push 2 + println("Primes after pushing 2 to the front $primes") + } +} diff --git a/lesson_07_maps/maps.groovy b/lesson_07_maps/maps.groovy new file mode 100644 index 0000000..a740c8d --- /dev/null +++ b/lesson_07_maps/maps.groovy @@ -0,0 +1,73 @@ +class GroovyMaps{ + static void main(String[] arg){ + // ---------- MAPS ---------- + // List of objects with keys versus indexes, similar to Python dict + + def paulMap = [ + 'name' : 'Paul', + 'age' : 35, + 'address' : '123 Main St', + 'list' : [1,2,3] + ]; + + // Access with key + println("Name " + paulMap['name']); + println("Age " + paulMap.get('age')); + println("List Item " + paulMap['list'][1]); + + // Add key value + paulMap.put('city', 'Pittsburgh'); + paulMap['zip'] = '09021' + paulMap.country = 'US' + + // Check for key + println("Has City " + paulMap.containsKey('city')); + + // Size + println("Size " + paulMap.size()); + + println("paulMap is $paulMap"); + + // Remove item + paulMap.remove('country'); + println("paulMap after country removed $paulMap"); + + //Collect entries method used for iterating through map transforming each + //entry + def colEntries = paulMap.collectEntries {key, value -> [value, key]}; + println colEntries; + + colEntries = paulMap.collectEntries {key, value -> [value, key.toUpperCase()]}; + println colEntries; + + //Create a map from a simple list + def simpleList = ["JAX", "ResearchIT", "Faculty", "Mice", "Computer Science"]; + def simpleMap = simpleList.collectEntries{ [(it.length()*2):it] }; + println("simpleList - $simpleList"); + println simpleMap; + + //Count items in a map + def numberMap = [nbr1: 11, nbr2: 12, nbr3: 13, nbr4: 14, nbr5: 15]; + println numberMap.count { it.value % 2 }; + //count a group of items which the value modulus by 2 equals 0 or 1 using + //the countBy method + println numberMap.countBy { it.value % 2 }; + + //Map Intersect + def map1 = [a: 1, b: 2, c: 3, d: 4, e: 5]; + def map2 = [a: 1, b: 6, c: 3, d: 8, e: 9]; + println map1; + println map2; + println("Intersect of map1 & map2 is " + map1.intersect(map2)); + + //Map iteration + map1.each {myvar -> println "$myvar.key:$myvar.value"}; + map1.eachWithIndex {myvar, idx -> println "$idx $myvar.key:$myvar.value"}; + + //Find from the Map + println map1.findAll { it.value > 2 }; + println map1.findAll { it.value < 2 }; + println map1.findAll { it.value == 3 }; + println map1.findAll { it.key == "d" }; + } +} diff --git a/lesson_08_range/range.groovy b/lesson_08_range/range.groovy new file mode 100644 index 0000000..8f1e66b --- /dev/null +++ b/lesson_08_range/range.groovy @@ -0,0 +1,55 @@ +class GroovyRange{ + static void main(String[] arg){ + // Ranges represent a range of values in shorthand notation + + def oneTo10 = 1..10; + def aToZ = 'a'..'z'; + def zToA = 'z'..'a'; + + println(oneTo10); + println(aToZ); + println(zToA); + + // Get size + println("Size " + oneTo10.size()); + + // get index + println("2nd Item " + oneTo10.get(1)); + + // Check if range contains + println("Contains 11 " + oneTo10.contains(11)); + println("Does it contain 3 and 6? " + oneTo10.containsAll([3,6])); + println("Does it contain 7 and 12? " + oneTo10.containsAll([7,12])); + + + // Get last item + println("Get Last " + oneTo10.getTo()); + + println("Get First " + oneTo10.getFrom()); + + //Iterate a range using for loop + for (num in oneTo10) { print("$num, ") }; + println(); + oneTo10.each { num -> print("$num, ") } + println(); + + for (letter in aToZ) { print("$letter, ") }; + println(); + aToZ.each { letter -> print("$letter, ") }; + println(); + + for (letter in zToA) { print("$letter, ") }; + println(); + zToA.each { letter -> print("$letter, ") }; + println(); + + //Use step to custmize increment + def odds = (1..10).step(2); //parens here needed for .step() + def evens = (2..10).step(2); + + odds.each { num -> print("$num, ") }; + println(); + evens.each { num -> print("$num, ") }; + println(); + } +} diff --git a/lesson_09_conditionals/conditionals.groovy b/lesson_09_conditionals/conditionals.groovy new file mode 100644 index 0000000..f5eb9c4 --- /dev/null +++ b/lesson_09_conditionals/conditionals.groovy @@ -0,0 +1,42 @@ +class GroovyConditionals{ + static void main(String[] arg){ + // ---------- CONDITIONALS ---------- + // Conditonal Operators : ==, !=, >, <, >=, <= + + // Logical Operators : && || ! + + def ageOld = 6; + + if(ageOld == 5){ + println("Go to Kindergarten"); + } else if((ageOld > 5) && (ageOld < 18)) { + printf("Go to grade %d \n", (ageOld - 5)); + } else { + println("Go to College"); + } + + def canVote = true; + + // Ternary operator + println(canVote ? "Can Vote" : "Can't Vote"); + + // Switch statement + switch(ageOld) { + case 16: println("You can drive"); + case 18: + println("You can vote"); + + // Stops checking the rest if true + break; + default: println("Have Fun"); + } + + // Switch with list options + switch(ageOld){ + case 0..6 : println("Toddler"); break; + case 7..12 : println("Child"); break; + case 13..18 : println("Teenager"); break; + default : println("Adult"); + } + } +} diff --git a/lesson_10_looping/looping.groovy b/lesson_10_looping/looping.groovy new file mode 100644 index 0000000..1c743cd --- /dev/null +++ b/lesson_10_looping/looping.groovy @@ -0,0 +1,58 @@ +class GroovyLooping{ + static void main(String[] arg){ + // ---------- LOOPING ---------- + // While loop + + def i = 0; + + while(i < 10){ + + // If i is odd skip back to the beginning of the loop + if(i % 2){ + i++; + continue; + } + + // If i equals 8 stop looping + if(i == 8){ + break; + } + + println(i); + i++; + } + + // Normal for loop + for (i = 0; i < 5; i++) { + println(i); + } + + // for loop with a range + for(j in 2..6){ + println(j); + } + + // for loop with a range and step + for(j in (2..6).step(2)){ + println(j); + } + + // for loop with a list (Same with string) + def randList = [10,12,13,14]; + + for(j in randList){ + println(j); + } + + // for loop with a map + def customers = [ + 100 : "Paul", + 101 : "Sally", + 102 : "Sue" + ]; + + for(customer in customers){ + println("$customer.value : $customer.key "); + } + } +} diff --git a/lesson_11_methods/methods.groovy b/lesson_11_methods/methods.groovy new file mode 100644 index 0000000..32db3c4 --- /dev/null +++ b/lesson_11_methods/methods.groovy @@ -0,0 +1,72 @@ +class GroovyMethods{ + // ------- Methods defined here ------- + + static def sayHello(){ + println("hello"); + } + + static def getSum(num1=0, num2=0){ + return num1 + num2 + } + + // Object passed to a method is pass by value not passing the object itself + static def passByValue(name){ + name = "In Function"; + println("Name : " + name); + } + + // Receive and return a list + static def doubleList(list){ + // Collect performs a calculation on every item in the list + def newList = list.collect { it * 2}; + return newList; + } + + // Pass unknown number of elements to a method + static def sumAll(int... num){ + def sum = 0; + + // Performs a calculation on every item with each + num.each { sum += it; } + return sum; + } + + // Calculate factorial (Recursion) + static def factorial(num){ + if(num <= 1){ + return 1; + } else { + return (num * factorial(num - 1)); + } + } + + static void main(String[] arg){ + // ---------- METHODS ---------- + // Methods allow us to break our code into parts and also + // allow us to reuse code + + sayHello(); + + // Pass parameters + println("5 + 4 = " + getSum(5,4)); + + // Demonstrate pass by value + def myName = "Derek"; + passByValue(myName); + println("In Main : " + myName); + + // Pass a list for doubling + def listToDouble = [1,2,3,4]; + listToDouble = doubleList(listToDouble); + println(listToDouble); + + // Pass unknown number of elements to a method + def nums = sumAll(1,2,3,4); + println("Sum : " + nums); + + // Calculate factorial (Recursion) + def fact4 = factorial(4); + println("Factorial 4 : " + fact4); + + } +} diff --git a/lesson_12_closure/closure.groovy b/lesson_12_closure/closure.groovy new file mode 100644 index 0000000..769de52 --- /dev/null +++ b/lesson_12_closure/closure.groovy @@ -0,0 +1,67 @@ +class GroovyClosure{ + static void main(String[] arg){ + // ---------- CLOSURES ---------- + // Closures represent blocks of code that can except parameters + // and can be passed into methods. + + // Alternative factorial using a closure + // num is the excepted parameter and call can call for + // the code to be executed + def getFactorial = { num -> (num <= 1) ? 1 : num * call(num - 1) } + println("Factorial 4 : " + getFactorial(4)); + + // A closure can access values outside of it + def greeting = "Goodbye"; + def sayGoodbye = {theName -> println("$greeting $theName")} + + sayGoodbye("Derek"); + + // each performs an operation on each item in list + def numList = [1,2,3,4]; + numList.each { println(it); } + + // Do the same with a map + def employees = [ + 'Paul' : 34, + 'Sally' : 35, + 'Sam' : 36 + ]; + + employees.each { println("${it.key} : ${it.value}"); } + + // Print only evens + def randNums = [1,2,3,4,5,6]; + randNums.each {num -> if(num % 2 == 0) println(num);} + + // find returns a match + def nameList = ['Doug', 'Sally', 'Sue']; + def matchEle = nameList.find {item -> item == 'Sue'} + println(matchEle); + + // findAll finds all matches + def randNumList = [1,2,3,4,5,6]; + def numMatches = randNumList.findAll {item -> item > 4} + println(numMatches); + + // any checks if any item matches + println("> 5 : " + randNumList.any {item -> item > 5}); + + // every checks that all items match + println("every num > 1?: " + randNumList.every {item -> item > 1}); + + // collect performs operations on every item + println("Double : " + randNumList.collect { item -> item * 2}); + + // pass closure to a method + def getEven = {num -> return(num % 2 == 0)} + def evenNums = listEdit(randNumList, getEven); + println("Evens : " + evenNums); + } + + // ---------- CLOSURES ---------- + // pass closure to a method + + static def listEdit(list, clo){ + return list.findAll(clo); + } +} diff --git a/lesson_13_file-IO/file-IO.groovy b/lesson_13_file-IO/file-IO.groovy new file mode 100644 index 0000000..b117e28 --- /dev/null +++ b/lesson_13_file-IO/file-IO.groovy @@ -0,0 +1,70 @@ +class GroovyFileIO{ + static void main(String[] arg){ + // ---------- FILE IO ---------- + // Open a file, read each line and output them + + File myfile = new File("test.txt") + + if (myfile.exists()) { + println("File exists!"); + } else { + println("File does NOT exist, will create file now."); + myfile.withWriter('utf-8') { + writer -> writer.writeLine("Line 1"); + } + myfile.append('Line 2\n'); + myfile.append('Line 3\n'); + } + + // Print each line of a file + myfile.eachLine { + line -> println "$line"; + } + + // Overwrite the file + myfile.withWriter('utf-8') { + writer -> writer.writeLine("Line 4"); + } + + // Sleep 3 seconds + sleep(3000); + + // Append the file + myfile.append('Line 5\n'); + + // Get the file as a string + println("Print file as string:\n$myfile.text"); + + // Get the file size + println("File Size : ${myfile.length()} bytes"); + + // Check if a file or directory + println("File : ${myfile.isFile()}"); + println("Dir : ${myfile.isDirectory()}"); + + // Copy file to another file + def newFile = new File("test2.txt"); + newFile << myfile.text; + + // Sleep 3 seconds + sleep(3000); + + // Delete a file + newFile.delete(); + + // Get directory files + def dirFiles = new File("").listRoots(); + dirFiles.each { + item -> println myfile.absolutePath; + } + + // Delete our test file + if (myfile.exists()) { + println("File exists and will delete it now."); + myfile.delete(); + } else { + println("File does NOT exist, will simply exit"); + } + + } +} diff --git a/lesson_14_OOP/Animal.groovy b/lesson_14_OOP/Animal.groovy new file mode 100644 index 0000000..3cfee33 --- /dev/null +++ b/lesson_14_OOP/Animal.groovy @@ -0,0 +1,24 @@ +import groovy.transform.ToString; + +// Creates the toString method +@ToString(includeNames=true, includeFields=true) +class Animal { + // Fields (Attributes) + def name; + def sound; + + // Methods (Capabilites) + def run(){ + println("${name} runs"); + } + + def makeSound(){ + println("${name} says ${sound}"); + } + + // Constructor Method + def Animal(name, sound){ + this.name = name; + this.sound = sound; + } +} diff --git a/lesson_14_OOP/Dog.groovy b/lesson_14_OOP/Dog.groovy new file mode 100644 index 0000000..21eb57a --- /dev/null +++ b/lesson_14_OOP/Dog.groovy @@ -0,0 +1,19 @@ +class Dog extends Animal{ + def owner; + + // Constructor Method + def Dog(name, sound, owner){ + // Call the Animal constructor + super(name, sound); + this.owner = owner; + } + + // Overwrite the Animal makeSound() + def makeSound(){ + println("${name} says bark and ${sound}"); + } + // Simple method for getting this dog object's owner + def getOwner(){ + return owner; + } +} diff --git a/lesson_14_OOP/Mammal.groovy b/lesson_14_OOP/Mammal.groovy new file mode 100644 index 0000000..db78832 --- /dev/null +++ b/lesson_14_OOP/Mammal.groovy @@ -0,0 +1,5 @@ +class Mammal extends Thing{ + def Mammal(name){ + this.name = name; + } +} diff --git a/lesson_14_OOP/OOP.groovy b/lesson_14_OOP/OOP.groovy new file mode 100644 index 0000000..0cde86d --- /dev/null +++ b/lesson_14_OOP/OOP.groovy @@ -0,0 +1,36 @@ +class GroovyOOP{ + static void main(String[] arg){ + // ---------- OOP ---------- + // Classes are blueprints that are used to define objects + // Every object has attributes (fields) and capabilities + // (methods) + + // Create an Animal object with named parameters + // def king = new Animal(name : 'King', sound : 'Growl'); + // or with a Constructor + def king = new Animal('King', 'Growl'); + + println("${king.name} says ${king.sound}"); + + // Change an object attribute with a setter + king.setSound('Grrrr'); + println("${king.name} says ${king.sound}"); + + king.run(); + + println(king.toString()); + + // With inheritance a class can inherit all fields + // and methods of another class + def cavalier = new Dog('Reegan', 'Grrrrr', 'Frank'); + + king.makeSound(); + cavalier.makeSound(); + println("$cavalier.name's owner is ${cavalier.getOwner()}") + + // Mammal inherits from the abstract class Thing + def hamster = new Mammal('Furry'); + hamster.getInfo(); + + } +} diff --git a/lesson_14_OOP/Thing.groovy b/lesson_14_OOP/Thing.groovy new file mode 100644 index 0000000..7385bd4 --- /dev/null +++ b/lesson_14_OOP/Thing.groovy @@ -0,0 +1,10 @@ +// An Abstract class can't be instantiated, but it +// can contain fields, and abstract or concrete methods +abstract class Thing{ + public String name; + public Thing() {} + + def getInfo(){ + println("The things name is ${name}"); + } +} diff --git a/lesson_14_OOP/Widget.groovy b/lesson_14_OOP/Widget.groovy new file mode 100644 index 0000000..ad0627d --- /dev/null +++ b/lesson_14_OOP/Widget.groovy @@ -0,0 +1,8 @@ +// An interface defines a contract that says any +// object that inherits from it will implement +// the methods defined by it +// All methods are abstract +interface Widget { + // Define abstract method that returns nothing + void doSomething(); +} diff --git a/lesson_15_exception-handling/exception-handling.groovy b/lesson_15_exception-handling/exception-handling.groovy new file mode 100644 index 0000000..5dca83b --- /dev/null +++ b/lesson_15_exception-handling/exception-handling.groovy @@ -0,0 +1,25 @@ +class GroovyExceptionHandling{ + static void main(String[] arg){ + // ---------- EXCEPTION HANDLING ---------- + // Handles runtime errors + + try { + File testFile; + testFile.append('Line 5'); + } + catch(NullPointerException ex){ + + // Prints exception + println("Caught exception: ${ex.toString()}"); + + // Prints error message + println("Caught error: ${ex.getMessage()}"); + } + catch(Exception ex){ + println("I Catch Everything"); + } + finally { + println("I perform clean up") + } + } +}