Saturday, November 13, 2010

Gosu - Basics by Example



Extending my Basics by Example series to a new language :D. today's version of the post written in Gosu Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Gosu Basics
classpath "."
//package gsgreetprogram
uses java.util.Calendar
uses java.util.GregorianCalendar
uses java.util.Scanner
uses java.lang.System

public class Greet {
    // Fields or Attributes
    private var _message: String
    private var _name: String
    private var _loopMessage: int
    // Properties
    public property get Message(): String {
        return this._message
    }
    public property set Message(value: String) {
        this._message = this.capitalize(value)
    }
    public property get Name(): String {
        return this._name 
    }
    public property set Name(value: String) {
        this._name = this.capitalize(value)
    }
    public property get LoopMessage(): int {
        return this._loopMessage
    }
    public property set LoopMessage(value: int) {
        this._loopMessage = value
    }
    // Constructor
    public construct() {
        this._message = ""
        this._name = ""
        this._loopMessage = 0
    }
    // Overloaded Constructor
    public construct(pmessage: String, pname: String, ploopMessage: int) {
        this._message = pmessage
        this._name = pname
        this._loopMessage = ploopMessage
    }
    // Method 1
    private function capitalize(val: String): String {
        // "if-then-else" statement
        if(val.length >= 1) {
            return val.capitalize()
        }
        else {
            return ""
        }
    }
    // Method 2
    public function salute() {
        // "for" statement        
        for (i in 0..this._loopMessage) {
            print("${this._message} ${this._name}!")
        }
    }
    // Overloaded Method 2.1
    public function salute(pmessage: String, pname: String, ploopMessage: int) {
        // "while" statement
        var i: int = 0
        while (i < ploopMessage) {
            print("${this.capitalize(pmessage)} ${this.capitalize(pname)}!")
            i = i + 1
        }
    }
    // Overloaded Method 2.2    
 public function salute(pname: String) {    
  // "switch/case" statement    
  var dtNow = new GregorianCalendar()
  switch (dtNow.get(Calendar.HOUR_OF_DAY))
  {    
   case 6: case 7: case 8: case 9: case 10: case 11:    
    this._message = "good morning,"
    break
   case 12: case 13: case 14: case 15: case 16: case 17:    
    this._message = "good afternoon,"
    break
   case 18: case 19: case 20: case 21: case 22:    
    this._message = "good evening,"
    break
   case 23: case 0: case 1: case 2: case 3: case 4: case 5:    
    this._message = "good night,"
    break
   default:    
    this._message = "huh?"
  }    
  print("${this.capitalize(this._message)} ${this.capitalize(pname)}!")
 }    
}

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor        
var g = new Greet()
// Call Set Properties        
g.Message = "hello"            
g.Name = "world"            
g.LoopMessage = 5
// Call Method 2            
g.salute()        
// Call Method 2.1 and Get Properties            
g.salute(g.Message, "gosu", g.LoopMessage)        
// Call Method 2.2            
g.salute("carlos")            
// Stop and exit            
print("Press any key to exit...")
var sin = new Scanner(System.in)
var line = sin.nextLine()
sin.close()

Greetings Program - Minimal
// Gosu Basics
classpath "."
uses java.util.Calendar
uses java.util.GregorianCalendar
uses java.util.Scanner
uses java.lang.System

class Greet {
    // Fields or Attributes
    var _message: String
    var _name: String
    var _loopMessage: int
    // Properties
    property get Message(): String {
        return _message
    }
    property set Message(value: String) {
        _message = capitalize(value)
    }
    property get Name(): String {
        return _name 
    }
    property set Name(value: String) {
        _name = capitalize(value)
    }
    property get LoopMessage(): int {
        return _loopMessage
    }
    property set LoopMessage(value: int) {
        _loopMessage = value
    }
    // Constructor
    construct() {
        _message = ""
        _name = ""
        _loopMessage = 0
    }
    // Overloaded Constructor
    construct(pmessage: String, pname: String, ploopMessage: int) {
        _message = pmessage
        _name = pname
        _loopMessage = ploopMessage
    }
    // Method 1
    private function capitalize(val: String): String {
        // "if-then-else" statement
        if(val.length >= 1) {
            return val.capitalize()
        }
        else {
            return ""
        }
    }
    // Method 2
    function salute() {
        // "for" statement        
        for (i in 0.._loopMessage) {
            print("${_message} ${_name}!")
        }
    }
    // Overloaded Method 2.1
    function salute(pmessage: String, pname: String, ploopMessage: int) {
        // "while" statement
        var i = 0
        while (i < ploopMessage) {
            print("${capitalize(pmessage)} ${capitalize(pname)}!")
            i = i + 1
        }
    }
    // Overloaded Method 2.2    
    function salute(pname: String) {
        // "switch/case" statement    
        var dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))
        {    
            case 6: case 7: case 8: case 9: case 10: case 11:    
                _message = "good morning,"
                break
            case 12: case 13: case 14: case 15: case 16: case 17:
                _message = "good afternoon,"
                break
            case 18: case 19: case 20: case 21: case 22:    
                _message = "good evening,"
                break
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:    
                _message = "good night,"
                break    
            default:    
                _message = "huh?"
        }    
        print("${capitalize(_message)} ${capitalize(pname)}!")
    }    
}

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor        
var g = new Greet()
// Call Set Properties        
g.Message = "hello"            
g.Name = "world"            
g.LoopMessage = 5
// Call Method 2            
g.salute()        
// Call Method 2.1 and Get Properties            
g.salute(g.Message, "gosu", g.LoopMessage)        
// Call Method 2.2            
g.salute("carlos")            
// Stop and exit            
print("Press any key to exit...")
var sin = new Scanner(System.in)
var line = sin.nextLine()
sin.close()


And the Output is:




Auto-Implemented Properties in Gosu

Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

// Gosu Basics
class AutoImplementedProperties {
    // Fields + Auto-Implemented Properties
    var _message: String as Message
    var _name: String as Name
    var _loopMessage: int as LoopMessage
    // Methods
    function salute() {
        print("${_message.capitalize()} ${_name.capitalize()} ${_loopMessage}!")
    }
}

var g = new AutoImplementedProperties()
// Call Set Properties
g.Message = "hello"
g.Name = "world"
g.LoopMessage = 5
// print them out
g.salute()
// and print them again using Get Properties
print(g.Message + " " + g.Name + " " + g.LoopMessage + "!")

And the output is:

Friday, November 12, 2010

OO Hello World - Gosu



The Hello World version of the program in Gosu!

A new OO programming language targeting the JVM with a Java-like syntax and compatible with java code. This looks like a promising language that deserves to be in the list of the ~20 languages I'm writing on here.

So, let's see how it looks like and how it compares to the other langs in a minimal OO program :D 


By the way, you can see my previous post here: http://carlosqt.blogspot.com/2010/06/oo-hello-world.html
where I give some details on WHY these "OO Hello World series" samples. 


Version 1 (Minimal):
The minimum you need to type to get your program compiled and running.

class Greet {
    var _name: String
    construct(name: String) {
        _name = name.capitalize()  
    }
    function salute() {
        print("Hello ${_name}!")
    }
}

// Greet Program
var g = new Greet("world")
g.salute()

Version 2 (Verbose):
Explicitly adding instructions and keywords that are optional to the compiler.

//classpath "."
//package greetprogram
uses java.util.*

public class Greet {
    private var _name: String
    public construct(name: String) {
        this._name = name.capitalize()  
    }
    public function salute() {
        print("Hello ${this._name}!")
    }
}

// Greet Program
var g = new Greet("world")
g.salute()

The Program Output:









Gosu Info:
“Gosu is an imperative statically-typed object-oriented programming language that is designed to be expressive, easy-to-read, and reasonably fast. Gosu supports several resource types” Taken from: (http://gosu-lang.org/intro.shtml)

Appeared:
2010
Current Version:
Developed by:
Guidewire Software
Creator:

Influenced by:
Java (James Gosling)
Predecessor Language

Predecessor Appeared

Predecessor Creator

Runtime Target:
JVM
Latest Framework Target:
JDK 6
Mono Target:
No
Allows Unmanaged Code:
No
Source Code Extension:
“.gsp”
Keywords:
53
Case Sensitive:
Yes
Free Version Available:
Yes
Open Source:
Yes
Standard:

Latest IDE Support:
Eclipse
IntelliJ IDEA
Language Reference:
Extra Info:


Monday, November 1, 2010

Oxygene - Basics by Example



Continue with the Basics by Example; today's version of the post written in Oxygene Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Delphi Prism Basics
namespace DPGreetProgram;  

interface
uses
    System;   
  
type 
    Greet = public class      
        // Fields of Attributes
        private var fMessage: String;            
        private var fName: String;
        private var fLoopMessage: Integer;
        // Methods Definition
        private method Capitalize(value: String): String;
        private method SetMessage(value: String);
        private method SetName(value: String);    
        // Properties
        public property Message: String read fMessage write SetMessage;
        public property Name: String read fName write SetName;
        public property LoopMessage: Integer read fLoopMessage write fLoopMessage;        
        // Constructors Definition
        public constructor();
        public constructor(message: String; name: String; loopMessage: Integer);  
        // Methods Definition
        public method Salute();
        public method Salute(message: String; name: String; loopMessage: Integer);  
        public method Salute(name: String);
    end;  
  
type  
    GreetProgram = public class      
    public class method Main(args: array of String);  
    end;

implementation
// Property Setters/Getters Methods
method Greet.SetMessage(value: String);
begin
    self.fMessage := self.Capitalize(value);
end;
method Greet.SetName(value: String);
begin
    self.fName := self.Capitalize(value);
end;
// Constructor 
constructor Greet();
begin
    self.fMessage := "";
    self.fName := "";
    self.loopMessage := 0;    
end;  
// Overloaded Constructor 
constructor Greet(message: String; name: String; loopMessage: Integer);
begin
    self.fMessage := message;
    self.fName := name;
    self.loopMessage := loopMessage;
end;
// Method 1
method Greet.Capitalize(value: String): String;
begin
    // "if-then-else" statement 
    if value.Length >= 1 then 
    begin
        result := value[0].ToString().ToUpper() + value.SubString(1, value.Length - 1);
    end
    else 
    begin
        result := "";
    end;
end;
// Method 2
method Greet.Salute();
begin  
    // "for" statement 
    for i: Integer := 1 to self.loopMessage step 1 do
    begin
        Console.WriteLine("{0} {1}!", self.fMessage, self.fName);
    end;
end;  
// Overloaded Method 2.1 
method Greet.Salute(message: String; name: String; loopMessage: Integer);
var
    i: Integer;
begin
    // "while" statement  
    i := 0;
    while i < loopMessage do 
    begin
        Console.WriteLine("{0} {1}!", self.Capitalize(message), self.Capitalize(name));
        i := i + 1;
    end;
end;
// Overloaded Method 2.2  
method Greet.Salute(name: String);
var    
    dtNow: DateTime;
begin
    // "switch/case" statement  
    dtNow := DateTime.Now;
    case dtNow.hour of
        6..11: self.fMessage := "good morning,";
        12..17: self.fMessage := "good afternoon,";
        18..22: self.fMessage := "good evening,";
        23,0..5: self.fMessage := "good night,";
        else self.fMessage := "huh?"; 
    end;
    Console.WriteLine("{0} {1}!", self.Capitalize(self.fMessage), self.Capitalize(name));
end;

// Console Program
class method GreetProgram.Main(args: array of String);  
var
    // Define object of type Greet    
    g: Greet;
begin  
    // Instantiate Greet. Call Constructor 
    g := new Greet();
    // Call Set Properties  
    g.Message := "hello";  
    g.Name := "world";  
    g.LoopMessage := 5;  
    // Call Method 2  
    g.Salute();  
    // Call Overloaded Method 2.1 and Get Properties  
    g.Salute(g.Message, "delphi Prism", g.LoopMessage);  
    // Call Overloaded Method 2.2  
    g.Salute("carlos");
    
    // Stop and exit  
    Console.WriteLine("Press any key to exit...");  
    Console.Read();  
end;  
end.


Greetings Program - Minimal
// Delphi Prism Basics
namespace;

interface
uses
    System;   
  
type
    Greet = class  
    private
        // Fields of Attributes
        fMessage: String;
        fName: String;
        fLoopMessage: Integer;
        // Methods Definition
        method Capitalize(value: String): String;
        method SetMessage(value: String);
        method SetName(value: String);
    public
        // Properties
        property Message: String read fMessage write SetMessage;
        property Name: String read fName write SetName;
        property LoopMessage: Integer read fLoopMessage write fLoopMessage;        
        // Constructors Definition
        constructor;
        constructor(message: String; name: String; loopMessage: Integer);  
        // Methods Definition
        method Salute;
        method Salute(message: String; name: String; loopMessage: Integer);  
        method Salute(name: String);
    end;  
  
type 
    GreetProgram = class
    public  
        class method Main(args: array of String);  
    end;

implementation
// Property Setters/Getters Methods
method Greet.SetMessage(value: String);
begin
    fMessage := Capitalize(value);
end;
method Greet.SetName(value: String);
begin
    fName := Capitalize(value);
end;
// Constructor 
constructor Greet;
begin
    fMessage := "";
    fName := "";
    loopMessage := 0;    
end;  
// Overloaded Constructor 
constructor Greet(message: String; name: String; loopMessage: Integer);
begin
    fMessage := message;
    fName := name;
    loopMessage := loopMessage;
end;
// Method 1
method Greet.Capitalize(value: String): String;
begin
    // "if-then-else" statement 
    if value.Length >= 1 then 
    begin
        result := value[0].ToString().ToUpper() + value.SubString(1, value.Length - 1);
    end
    else 
    begin
        result := "";
    end;
end;
// Method 2
method Greet.Salute;
begin  
    // "for" statement 
    for i: Integer := 1 to loopMessage step 1 do
    begin
        Console.WriteLine("{0} {1}!", fMessage, fName);
    end;
end;  
// Overloaded Method 2.1 
method Greet.Salute(message: String; name: String; loopMessage: Integer);
var
    i: Integer;
begin
    // "while" statement  
    i := 0;
    while i < loopMessage do 
    begin
        Console.WriteLine("{0} {1}!", Capitalize(message), Capitalize(name));
        i := i + 1;
    end;
end;
// Overloaded Method 2.2  
method Greet.Salute(name: String);
var    
    dtNow: DateTime;
begin
    // "switch/case" statement  
    dtNow := DateTime.Now;
    case dtNow.hour of
        6..11: fMessage := "good morning,";
        12..17: fMessage := "good afternoon,";
        18..22: fMessage := "good evening,";
        23,0..5: fMessage := "good night,";
        else fMessage := "huh?"; 
    end;
    Console.WriteLine("{0} {1}!", Capitalize(fMessage), Capitalize(name));
end;

// Console Program
class method GreetProgram.Main(args: array of String);  
var
    // Define object of type Greet    
    g: Greet;
begin  
    // Instantiate Greet. Call Constructor 
    g := new Greet();
    // Call Set Properties  
    g.Message := "hello";  
    g.Name := "world";  
    g.LoopMessage := 5;  
    // Call Method 2  
    g.Salute;
    // Call Overloaded Method 2.1 and Get Properties  
    g.Salute(g.Message, "delphi Prism", g.LoopMessage);  
    // Call Overloaded Method 2.2      
    g.Salute("carlos");    
    // Stop and exit  
    Console.WriteLine("Press any key to exit...");  
    Console.Read();  
end;  
end.

And the Output is:





















Auto-Implemented Properties in Delphi Prism
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

namespace;
interface
uses System;   

type Greet = class  
    // No explicit private field required
    // private fMessage: String;
    // Auto Implemented Property
    property Message: String;
    constructor();        
    method Salute();        
    method Salute(value: String);
end;  

type GreetProgram = class
    class method Main(args: array of String);  
end;

implementation
// Constructor 
constructor Greet();
begin
    Message := "";
end;  
method Greet.Salute();
begin  
    Console.WriteLine(Message[0].ToString().ToUpper() + Message.SubString(1, Message.Length - 1));
end;  
method Greet.Salute(value: String);
begin  
    Console.WriteLine(value[0].ToString().ToUpper() + value.SubString(1, value.Length - 1));
end; 

class method GreetProgram.Main(args: array of String);  
var g: Greet;
begin  
    g := new Greet();
    // Call Set Auto Implemented Property
    g.Message := "hello";  
    g.Salute;
    g.Message := "bye";
    // Call Get Auto Implemented Property
    g.Salute(g.Message);
end;  
end.


And the Output is:

Sunday, October 31, 2010

Halloween Programming Languages



Happy Halloween to everybody!

What are the most horrifying Programming Languages you have came across or at least read on the Internet? Those languages that if someone come to you and ask you to Maintain or Extend a program written on them you will probably refuse or at least think twice before accepting?

Here below some of them, which I will certainly say "NO, thanks" straight away.


Malbolge

Malbolge is a public domain esoteric programming language invented by Ben Olmstead in 1998, named after the eighth circle of hell in Dante's Inferno, the Malebolge.

The peculiarity of Malbolge is that it was designed to be the most difficult and esoteric programming language. However, several of the tricks used to make understanding it difficult can be simplified away.

Malbolge was so difficult to understand when it arrived that it took two years for the first Malbolge program to appear. The program was not even written by a human being: it was generated by a beam search algorithm designed by Andrew Cooke and implemented in Lisp.

"Hello world" in Malbolge







(more on Malbolge in:  http://en.wikipedia.org/wiki/Malbolge)

Whitespace

Whitespace is an esoteric programming language developed by Edwin Brady and Chris Morris at the University of Durham (also developers of the Kaya programming language). It was released on 1 April 2003 (April Fool's Day). Its name is a reference to whitespace characters. Unlike most programming languages, which ignore or assign little meaning to most whitespace characters, the Whitespace interpreter ignores any non-whitespace characters. Only spaces, tabs and linefeeds have meaning.[1] An interesting consequence of this property is that a Whitespace program can easily be contained within the whitespace characters of a program written in another language, making the text a polyglot.

The language itself is an imperative stack-based language. The virtual machine on which the programs run has a stack and a heap. The programmer is free to push arbitrary width integers onto the stack (currently there is no implementation of floating point numbers) and can also access the heap as a permanent store for variables and data structures.

"Hello world" in Whitespace
Pink = Space and Purple = Tab




































(more on Whitespace in:  http://en.wikipedia.org/wiki/Whitespace_(programming_language))


Brainfuck

The brainfuck programming language is an esoteric programming language noted for its extreme minimalism. It is a Turing tarpit, designed to challenge and amuse programmers, and is not suitable for practical use.[1] Its name has been variously bowdlerized. The name of the language is generally not capitalized except at the start of a sentence, although it is a proper noun.

Urban Müller created brainfuck in 1993 with the intention of designing a language which could be implemented with the smallest possible compiler,[2] inspired by the 1024-byte compiler for the FALSE programming language.[3] Several brainfuck compilers have been made smaller than 200 bytes. The classic distribution is Müller's version 2, containing a compiler for the Amiga, an interpreter, example programs, and a readme document.

The language consists of eight commands, listed below. A brainfuck program is a sequence of these commands, possibly interspersed with other characters (which are ignored). The commands are executed sequentially, except as noted below; an instruction pointer begins at the first command, and each command it points to is executed, after which it normally moves forward to the next command. The program terminates when the instruction pointer moves past the last command.

"Hello world" in Brainfuck





(more on Brainfuck in:  http://en.wikipedia.org/wiki/Brainfuck)

Definitions and info of each programming language mentioned on this post as well as the hello world examples were taken from Wikipedia.org :)

If you want to know more about each of those languages and others you can find them here:
http://en.wikipedia.org/wiki/Category:Esoteric_programming_languages

What other languages do you think can be listed here?
I was thinking about Assembler, even if for some might be easy, but for those of us that started with structured or object oriented high level languages it looks little bit cryptic.

JRuby - Basics by Example



Continue with the Basics by Example; today's version of the post written in JRuby Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
# JRuby basics  
require "java"  
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System

module RbGreetProgram  
    class Greet  
        # Fields or Attributes  
        @message = ""  
        @name = ""  
        @loopMessage = 0  
        # Properties | Getters, Setters  
        def message  
          @message  
        end  
        def message=(val)  
          @message = capitalize(val)  
        end  
        def name  
          @name  
        end  
        def name=(val)  
          @name = capitalize(val)  
        end  
        def loopMessage  
          @loopMessage  
        end  
        def loopMessage=(val)  
          @loopMessage = val  
        end  
        # Constructor or Initializer Method  
        def initialize  
            @message = ""  
            @name = ""  
            @loopMessage = 0  
        end  
        # Overloaded Constructor  
        # No Overloaded Constructors/Initializers Support in Ruby  
        # Method 1  
        def capitalize(val)  
            # "if-then-else" statement  
            if val.length >= 1  
                return val.capitalize  
            else  
                return ""  
            end  
        end  
        private :capitalize  
        # Method 2  
        def salute  
            # "for" statement  
            for i in 0..@loopMessage  
                puts "#@message #@name!"  
            end  
        end  
        # Overloaded Method  
        # No Overloaded Methods Support in Ruby. New methods instead.  
         # Method 2.1  
        def salute21(message, name, loopMessage)  
            # "while" statement  
            i = 0  
            while i < loopMessage do  
                puts "#{capitalize(message)} #{capitalize(name)}!"  
                i += 1  
            end  
        end  
        # Method 2.2  
        def salute22(name)  
            # "switch/case" statement  
            dtNow = GregorianCalendar.new            
            @message = case dtNow.get(Calendar::HOUR_OF_DAY)
                when 6..11 then "good morning,"  
                when 12..17 then "good afternoon,"  
                when 18..22 then "good evening,"  
                when 23,0..5 then "good night,"  
                else "huh?"  
            end  
            puts "#{capitalize(@message)} #{capitalize(name)}!"  
        end  
    end  
  
    # Console Program  
    # Define variable object of type Greet  
    # Instantiate Greet. Call Constructor  
    g = Greet.new  
    # Call Set Properties  
    g.message = "hello"  
    g.name = "world"  
    g.loopMessage = 5  
    # Call Method 2  
    g.salute()  
    # Call Method 2.1 and Get Properties  
    g.salute21(g.message, "jRuby", g.loopMessage)  
    # Call Method 2.2  
    g.salute22("carlos")  
    # Stop and exit  
    puts "Press any key to exit..."  
    gets  
end


Greetings Program - Minimal
# JRuby basics  
require "java"  
import java.util.GregorianCalendar
import java.util.Calendar
import java.lang.System

class Greet  
    # Fields or Attributes  
    @message = ""  
    @name = ""  
    @loopMessage = 0  
    # Properties | Getters, Setters  
    def message  
      @message  
    end  
    def message=(val)  
      @message = capitalize(val)  
    end  
    def name  
      @name  
    end  
    def name=(val)  
      @name = capitalize(val)  
    end  
    def loopMessage  
      @loopMessage  
    end  
    def loopMessage=(val)  
      @loopMessage = val  
    end  
    # Constructor or Initializer Method  
    def initialize  
        @message = ""  
        @name = ""  
        @loopMessage = 0  
    end  
    # Overloaded Constructor  
    # No Overloaded Constructors/Initializers Support in Ruby  
    # Method 1  
    def capitalize(val)  
        # "if-then-else" statement  
        if val.length >= 1  
            return val.capitalize  
        else  
            return ""  
        end  
    end  
    private :capitalize  
    # Method 2  
    def salute  
        # "for" statement  
        for i in 0..@loopMessage  
            puts "#@message #@name!"  
        end  
    end  
    # Overloaded Method  
    # No Overloaded Methods Support in Ruby. New methods instead.  
    # Method 2.1  
    def salute21(message, name, loopMessage)  
        # "while" statement  
        i = 0  
        while i < loopMessage do  
            puts "#{capitalize(message)} #{capitalize(name)}!"  
            i += 1  
        end  
    end  
    # Method 2.2  
    def salute22(name)  
        # "switch/case" statement  
        dtNow = GregorianCalendar.new            
        @message = case dtNow.get(Calendar::HOUR_OF_DAY)
            when 6..11 then "good morning,"  
            when 12..17 then "good afternoon,"  
            when 18..22 then "good evening,"  
            when 23,0..5 then "good night,"  
            else "huh?"  
        end  
        puts "#{capitalize(@message)} #{capitalize(name)}!"  
    end  
end  
  
# Console Program  
# Define variable object of type Greet     
# Instantiate Greet. Call Constructor     
g = Greet.new  
# Call Set Properties     
g.message = "hello"       
g.name = "world"       
g.loopMessage = 5  
# Call Method 2       
g.salute()     
# Call Method 2.1 and Get Properties       
g.salute21(g.message, "jRuby", g.loopMessage)     
# Call Method 2.2  
g.salute22("carlos")
# Stop and exit
puts "Press any key to exit..."
gets



And the Output is:





















Where to define Class Fields/Attributes in JRuby

puts "Class Attributes Example:"  
class ClassAttributes  
    # You do not need to explicitly add the Fields/Attributes as shown below within the class:  
    # message = ""  
    # name = ""  
    # loopMessage = 0  
    # because they are added to the class as Fields/Attributes the first time they appear in  
    # your code. For example, here below, in the Initialize method,  
    # we have 2 fields (name and message)  
    def initialize  
        @message = "message" # class field  
        @name = "name"  # class field  
    end  
    # and one more within a public method (loopMessage)  
    def salute  
        @loopMessage = 1 # class field  
        localtest = 0   # local variable    
        puts "#@message, #@name, #@loopMessage"  
    end  
end  
  
# Then, you can access each of them as you normally do:  
f = ClassAttributes.new  
f.salute


Auto-Implemented Properties in JRuby
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

puts ""  
puts "Auto-Implemented Properties Example:"  
# Ruby basics  
class Greet  
    # Fields or Attributes  
    #@message = ""  
    # Manual Properties | Getters, Setters  
    #def message  
    # @message  
    #end  
    #def message=(val)  
    #  @message = capitalize(val)  
    #end  
      
    # Instead of creating a field and a manual property (as above)  
    # we use the attributes syntax to create our Auto-Implemented Property  
    # that will be linked to our @message class field/attribute  
    attr_accessor :message  
    # you can also create read or write only props using attr_writer|attr_reader  
      
    def initialize  
        @message = ""  
    end  
    def salute  
        puts "#@message"  
    end  
end  
  
g = Greet.new  
# we set the value of message through our write property  
g.message = "hello ruby"  
g.salute  
# or get the value from it as well  
puts g.message


Overloading Constructor and Methods in JRuby

Ruby does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elseif code to handle both(or multiple) cases yourself.

puts ""  
puts "Overloaded-like Constructor and Method Example:"  
class Overloading  
    # Constructor with variable arguments  
    def initialize(*args)  
        # if args list/sequence is not empty we use the arguments,  
        # otherwise we use the class fields  
        if args.size > 0  
            @message = args[0]  
            @name = args[1]  
            @loopMessage = args[2]  
        else  
            @message = 'empty_message'  
            @name = 'empty_name'  
            @loopMessage = 2  
        end  
    end  
    # Method  with variable arguments  
    def salute(*args)  
        # if args list/sequence is not empty we use the arguments,  
        # otherwise we use the class fields  
        if args.size > 0  
            for i in 1..args[2]  
                puts "#{args[0]}, #{args[1]}!"  
            end  
        else  
            for i in 1..@loopMessage  
                puts "#@message, #@name!"  
            end  
        end  
    end  
end  
  
# and now we use the "overloaded-like" constructor and method  
# calling constructor without parameters  
o1 = Overloading.new  
# calling method without parameters  
o1.salute  
# calling method with parameters  
o1.salute("Hello", "JRuby", 3)  
# calling constructor with with parameters  
o2 = Overloading.new("Hello", "Carlos", 2)  
# calling method without parameters  
o2.salute



And the Output is:




Saturday, October 30, 2010

Jython - Basics by Example



Continue with the Basics by Example; today's version of the post written in Jython Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
# Jython Basics  
import java
from java.util import GregorianCalendar, Calendar, Scanner
from java.lang import System
  
class Greet(object):  
    # Fields of Attributes  
    __message = ''  
    __name = ''    
    __loopMessage = 0  
    # Properties   
    def getMessage(self):   
        return self.__message  
    def setMessage(self, value):   
        self.__message = self.__capitalize(value)  
    Message = property(getMessage, setMessage)  
    def getName(self):   
        return self.__name  
    def setName(self, value):   
        self.__name = self.__capitalize(value)  
    Name = property(getName, setName)  
    def getLoopMessage(self):   
        return self.__loopMessage  
    def setLoopMessage(self, value):   
        self.__loopMessage = value  
    LoopMessage = property(getLoopMessage, setLoopMessage)  
    # Constructor or Initializer Method  
    def __init__(self):    
        self.__message = ''    
        self.__name = ''    
        self.__loopMessage = 0  
    # Overloaded Constructor    
    # No Overloaded Constructors Support in Python  
    # Method 1  
    def __capitalize(self, val):  
        # "if-then-else" statement    
        if len(val) >= 1:    
            return val.capitalize()  
        else:    
            return ""  
    # Method 2    
    def salute(self):    
    # "for" statement  
        for i in range(0, self.__loopMessage):  
            print self.__message, self.__name + '!'  
    # Overloaded Method  
    # No Overloaded Methods Support in Python. New methods instead.  
    # Method 2.1    
    def salute21(self, message, name, loopMessage):  
        # "while" statement  
        i = 0  
        while i < loopMessage:    
            print self.__capitalize(message), self.__capitalize(name) + '!'     
            i = i + 1  
    # Method 2.2  
    def salute22(self, name):    
        # "switch/case" statement is not supported      
        # so I'm using if then else if...   
        dtNow = GregorianCalendar()
        hh = dtNow.get(Calendar.HOUR_OF_DAY)
        if hh in range(6,12):      
            self.__message = "good morning,"      
        elif hh in range(12,18):      
            self.__message = "good evening,"      
        elif hh in range(18,23):      
            self.__message = "good afternoon,"      
        elif hh == 23 or hh in range(0,6):      
            self.__message = "good night,"    
        else:    
            self.__message = "huh?"    
        print self.__capitalize(self.__message), self.__capitalize(name) + '!'  
  
# Console Program  
def main():  
    # Define variable object of type Greet  
    # Instantiate Greet. Call Constructor  
    g = Greet()    
    # Call Set Properties  
    g.Message = "hello"    
    g.Name = "world"    
    g.LoopMessage = 5   
    # Call Method 2    
    g.salute()  
    # Call Method 2.1 and Get Properties    
    g.salute21(g.Message, "jython", g.LoopMessage)  
    # Call Method 2.2    
    g.salute22("carlos")    
    # Stop and exit    
    print "Press any key to exit..."    
    sin = Scanner(System.in)  
    line = sin.nextLine()  
    sin.close()  

main()

Greetings Program - Minimal
# Jython Basics  
from java.util import GregorianCalendar, Calendar, Scanner
from java.lang import System
  
class Greet(object):  
    # Fields of Attributes  
    __message = ''  
    __name = ''    
    __loopMessage = 0  
    # Properties   
    def getMessage(self):   
        return self.__message  
    def setMessage(self, value):   
        self.__message = self.__capitalize(value)  
    Message = property(getMessage, setMessage)  
    def getName(self):   
        return self.__name  
    def setName(self, value):   
        self.__name = self.__capitalize(value)  
    Name = property(getName, setName)  
    def getLoopMessage(self):   
        return self.__loopMessage  
    def setLoopMessage(self, value):   
        self.__loopMessage = value  
    LoopMessage = property(getLoopMessage, setLoopMessage)  
    # Constructor or Initializer Method  
    def __init__(self):    
        self.__message = ''    
        self.__name = ''    
        self.__loopMessage = 0  
    # Overloaded Constructor    
    # No Overloaded Constructors Support in Python  
    # Method 1  
    def __capitalize(self, val):  
        # "if-then-else" statement    
        if len(val) >= 1:    
            return val.capitalize()  
        else:    
            return ""  
    # Method 2    
    def salute(self):    
        # "for" statement  
        for i in range(0, self.__loopMessage):  
            print self.__message, self.__name + '!'  
    # Overloaded Method  
    # No Overloaded Methods Support in Python. New methods instead.  
    # Method 2.1    
    def salute21(self, message, name, loopMessage):  
        # "while" statement  
        i = 0  
        while i < loopMessage:    
            print self.__capitalize(message), self.__capitalize(name) + '!'     
            i = i + 1  
    # Method 2.2  
    def salute22(self, name):    
        # "switch/case" statement is not supported      
        # so I'm using if then else if...   
        dtNow = GregorianCalendar()
        hh = dtNow.get(Calendar.HOUR_OF_DAY)
        if hh in range(6,12):      
            self.__message = "good morning,"      
        elif hh in range(12,18):      
            self.__message = "good evening,"      
        elif hh in range(18,23):      
            self.__message = "good afternoon,"      
        elif hh == 23 or hh in range(0,6):      
            self.__message = "good night,"  
        else:    
            self.__message = "huh?"    
        print self.__capitalize(self.__message), self.__capitalize(name) + '!'  
  
# Console Program  
# Define variable object of type Greet  
# Instantiate Greet. Call Constructor  
g = Greet()    
# Call Set Properties  
g.Message = "hello"    
g.Name = "world"    
g.LoopMessage = 5   
# Call Method 2  
g.salute()  
# Call Method 2.1 and Get Properties    
g.salute21(g.Message, "jython", g.LoopMessage)  
# Call Method 2.2    
g.salute22("carlos")  
# Stop and exit    
print "Press any key to exit..."    
sin = Scanner(System.in)  
line = sin.nextLine()  
sin.close()


And the Output is:




















Private Fields and Methods in Jython

"There is limited support for class-private identifiers. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, variables stored in globals, and even variables stored in instances. private to this class on instances of other classes.

Name mangling is intended to give classes an easy way to define 'private' instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger, and that's one reason why this loophole is not closed. (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.)". Taken from: "http://docs.python.org/release/2.5.2/tut/node11.html#SECTION0011600000000000000000"

print 'Private Access Modifier Example:'  
class Greet(object):  
    # Fields of Attributes  
    __message = ''  
    __name = ''    
    __loopMessage = 0      
    # Constructor or Initializer Method  
    def __init__(self):    
        self.__message = ''    
        self.__name = ''    
        self.__loopMessage = 0   
    # Private Method  
    def __capitalize(self, val):  
        if len(val) >= 1:    
            return val.capitalize()  
        else:    
            return ""  
    # Public Method  
    def Salute(self):         
        for i in range(0, self.__loopMessage):
            print self.__message, self.__name + '!'
  
g = Greet()    
# publicly accessing private fields (_classname__fieldname)  
g._Greet__message = "hello"    
g._Greet__name = "world"    
g._Greet__loopMessage = 5   
# Call Public Method  
g.Salute()  
# Call Private Method (_classname__methodname)  
print g._Greet__capitalize('capitalized!')

Where to define Class Fields/Attributes in Jython

print ''  
print 'Class Attributes Example:'  
class ClassAttributes(object):  
    # You do not need to explicitly add the Fields/Attributes as shown below within the class:  
    # message = ''  
    # name = ''    
    # loopMessage = 0      
    # because they are added to the class as Fields/Attributes the first time they appear in   
    # your code. For example, here below, in the Initialize method,   
    # we have 2 fields (name and message)  
    def __init__(self):    
        self.message = '' # class field  
        self.name = ''  # class field  
    # and one more within a public method (loopMessage)  
    def Salute(self):  
        self.loopMessage = 0 # class field  
        localtest = 0   # local variable  
  
# Then, you can access each of them as you normally do:  
f = ClassAttributes()  
f.message = 'Hello'  
f.name = 'World'  
f.loopMessage = 5  
  
print f.message, f.name, f.loopMessage

Overloading Constructor and Methods in Jython

Python does not support Overloading Methods nor Constructors, instead, you can define one method with variable arguments and code the if-elif code to handle both(or multiple) cases yourself.

print ''  
print 'Overloaded-like Constructor and Method Example:'  
  
class Overloading(object):  
    # Constructor with variable arguments  
    def __init__(self, *args):  
        # if args list/sequence is not empty we use the arguments,   
        # otherwise we use the class fields
        if args:     
            self.message = args[0]  
            self.name = args[1]  
            self.loopMessage = args[2]  
        else:
            self.message = 'empty_message'  
            self.name = 'empty_name'  
            self.loopMessage = 2   
    # Method  with variable arguments  
    def Salute(self, *args):  
        # if args list/sequence is not empty we use the arguments,   
        # otherwise we use the class fields  
        if args:
            for i in range(0, args[2]):
                print args[0], args[1] + '!'  
        else:  
            for i in range(0, self.loopMessage):  
                print self.message, self.name + '!'     

# and now we use the "overloaded-like" constructor and method  
# calling constructor without parameters  
o1 = Overloading()  
# calling method without parameters  
o1.Salute()  
# calling method with parameters  
o1.Salute('Hello', 'Jython', 3)  
# calling constructor with with parameters  
o2 = Overloading('Hello', 'Carlos', 2)  
# calling method without parameters  
o2.Salute()


And the Output is:





Fantom - Basics by Example



Continue with the Basics by Example; today's version of the post written in Fantom Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Fantom Basics
internal class Greet  
{
    // Fields or Attributes
    private Str? message  
    private Str? name 
    private Int? loopMessage 
    // Properties, Getters and Setters
    public Str Message
    { 
      get { return this.&message }
      set { this.&message = this.capitalize(it) }
    }
    public Str Name
    { 
      get { return this.&name }
      set { this.&name = this.capitalize(it) }
    }
    public Int LoopMessage
    { 
      get { return this.&loopMessage }
      set { this.&loopMessage = it }
    }
    // Constructor
    public new make()
    {   
        this.message = ""
        this.name = ""
        this.loopMessage = 0
    }  
    // Overloaded Constructor
    // No Overloaded Constructor support as designed
    // Method 1
    private Str capitalize(Str val)
    {
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val.capitalize()
        }  
        else  {  
            return ""
        }  
    }
    // Method 2
    public Void salute() 
    {  
        // "for" statement
        for (i:=1; i<=this.loopMessage; i++) 
        {  
            echo("$this.message $this.name!")  
        }  
    }  
    // Overloaded Method
    // No Overloaded Methods Support in Fantom. News methods instead.
    // Method 2.1  
    public Void salute21(Str message, Str name, Int loopMessage) 
    {  
        // "while" statement  
        Int i := 0
        while(i < loopMessage) 
        {  
            echo("${this.capitalize(message)} ${this.capitalize(name)}!")            
            i++
        }  
    }  
    // Method 2.2
    public Void salute22(Str name) 
    {
        // "switch/case" statement  
        DateTime dtNow := DateTime.now();
        switch(dtNow.hour)
        {
            case 6: case 7: case 8: case 9: case 10: case 11:  
                this.message = "good morning," 
            case 12: case 13: case 14: case 15: case 16: case 17:  
                this.message = "good afternoon,"
            case 18: case 19: case 20: case 21: case 22:  
                this.message = "good evening," 
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                this.message = "good night,"
            default:
                this.message = "huh?" 
        }
        echo("${this.capitalize(this.message)} ${this.capitalize(name)}!")            
    }
}  

// Console Program
public class FanGreetProgram  
{  
    public static Void main()  
    {  
        // Define variable object of type Greet and Instantiate. Call Constructor
        Greet g := Greet.make()
        // Call Setters
        g.Message = "hello"
        g.Name = "world"
        g.LoopMessage = 5
        // Call Method 2    
        g.salute()  
        // Overloaded Method 2.1 and Getters    
        g.salute21(g.Message, "fantom", g.LoopMessage)   
        // Overloaded Method 2.2    
        g.salute22("carlos")  

        // Stop and exit    
        echo("Press any key to exit...")
        console := Env.cur
        userInput := console.in.readLine
    }  
}

Greetings Program - Minimal
// Fantom Basics
class Greet  
{
    // Fields or Attributes
    private Str? message  
    private Str? name 
    private Int? loopMessage 
    // Properties, Getters and Setters
    Str Message
    { 
      get { return &message }
      set { &message = capitalize(it) }
    }
    Str Name
    { 
      get { return &name }
      set { &name = capitalize(it) }
    }
    Int LoopMessage
    { 
      get { return &loopMessage }
      set { &loopMessage = it }
    }
    // Constructor
    new make()
    {   
        message = ""
        name = ""
        loopMessage = 0
    }  
    // Overloaded Constructor
    // No Overloaded Constructor support as designed
    // Method 1
    private Str capitalize(Str val)
    {
        // "if-then-else" statement  
        if (val.size >= 1) {  
            return val.capitalize
        }  
        else  {  
            return ""
        }  
    }
    // Method 2
    Void salute() 
    {  
        // "for" statement
        for (i:=1; i<=loopMessage; i++) 
        {  
            echo("$message $name!")  
        }  
    }  
    // Overloaded Method
    // No Overloaded Methods Support in Fantom. News methods instead.
    // Method 2.1  
    Void salute21(Str message, Str name, Int loopMessage) 
    {  
        // "while" statement  
        Int i := 0
        while(i < loopMessage) 
        {              
            echo("${capitalize(message)} ${capitalize(name)}!")
            i++  
        }  
    }  
    // Method 2.2
    Void salute22(Str name) 
    {
        // "switch/case" statement  
        DateTime dtNow := DateTime.now;
        switch(dtNow.hour)
        {
            case 6: case 7: case 8: case 9: case 10: case 11:  
                message = "good morning," 
            case 12: case 13: case 14: case 15: case 16: case 17:  
                message = "good afternoon,"
            case 18: case 19: case 20: case 21: case 22:  
                message = "good evening," 
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                message = "good night,"
            default:
                message = "huh?" 
        }
        echo("${capitalize(message)} ${capitalize(name)}!")
    }
}  

// Console Program
class FanGreetProgram  
{  
    static Void main()  
    {  
        // Define variable object of type Greet and Instantiate. Call Constructor
        Greet g := Greet()
        // Call Setters
        g.Message = "hello"
        g.Name = "world"
        g.LoopMessage = 5
        // Call Method 2    
        g.salute
        // Overloaded Method 2.1 and Getters    
        g.salute21(g.Message, "fantom", g.LoopMessage)   
        // Overloaded Method 2.2    
        g.salute22("carlos")  

        // Stop and exit    
        echo("Press any key to exit...")
        console := Env.cur
        userInput := console.in.readLine
    }  
}


And the Output is:


















Emulating Overloaded Constructor in Fantom
Fantom does not support Overloading Constructors by design, but you can some how "emulate" it by calling the constructor with an initializers list as shown here below.
class Greet  
{
    // defining public fields
    Str? message  
    Str? name 
    Int? loopMessage
    // Constructor
    new make()    
    {   
        echo("greet.make")
        message = "empty_message"
        name = "empty_name"
        loopMessage = 0
    }          
    // Method 2  
    Void Salute()  
    {  
        echo("$this.loopMessage $this.message $this.name!")
    }  
}  

class Program  
{  
    static Void main()  
    {  
        // calling constructor (printing greet.make)
        Greet g := Greet()        
        g.Salute()
        // calling constructor (printing greet.make) and explicitly assigning values to each field
        // this can be done if the fields are defined as public 
        // or you will get a Private field xxx not accessible
        Greet g2 := Greet{ message="hello"; name="world"; loopMessage=5 }
        g2.Salute()
    }  
}

And the Output is:

Friday, October 29, 2010

Groovy - Basics by Example



Continue with the Basics by Example; today's version of the post written in Groovy Enjoy!

You can copy and paste the code below in your favorite IDE/Editor and start playing and learning with it. This little "working" program will teach you the basics of the Programming Language.

There are some "comments" on the code added just to tell you what are or how are some features called. In case you want to review the theory, you can read my previous post, where I give a definition of each of the concepts mentioned on the code. You can find it here: http://carlosqt.blogspot.com/2010/08/new-series-languages-basics-by-example.html 


Greetings Program - Verbose
// Groovy Basics
package GvyGreetProgram

public class Greet {
    // Fields or Attributes
    private String message
    private String name
    private Integer loopMessage    
    // Properties or Getters and Setters
    public String getMessage() {  
        return this.message
    }  
    public void setMessage(String val) {  
        this.message = this.Capitalize(val)
    }  
    public String getName() {  
        return this.name
    }  
    public void setName(String val) {  
        this.name = this.Capitalize(val) 
    }  
    public Integer getLoopMessage() {  
        return this.loopMessage
    }  
    public void setLoopMessage(Integer val) {
        this.loopMessage = val
    }
    // Constructor  
    public def Greet() {  
        this.message = ""
        this.name = ""
        this.loopMessage = 0
    }  
    // Overloaded Constructor  
    public def Greet(String message, String name, Integer loopMessage) {  
        this.message = this.Capitalize(message)
        this.name = this.Capitalize(name)
        this.loopMessage = loopMessage
    }
    // Method 1
    private String Capitalize(String val) {  
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val[0].toUpperCase() + val[1..-1]  
        }  
        else  {  
            return "";  
        }  
    }  
    // Method 2  
    public void Salute() {  
        // "for" statement  
        for (i in 1..this.loopMessage) {  
            println "${this.message} ${this.name}!"  
        }  
    }  
    // Overloaded Method 2.1  
    public void Salute(String message, String name, Integer loopMessage) {  
        // "while" statement  
        Integer i = 0
        while(i < loopMessage) {  
            println "${this.Capitalize(message)} ${this.Capitalize(name)}!" 
            i++  
        }  
    }  
    // Overloaded Method 2.2  
    public void Salute(String name) {  
        // "switch/case" statement  
        def dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                this.message = 'good morning,' 
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                this.message = 'good afternoon,'
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                this.message = 'good evening,' 
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                this.message = 'good night,'
                break;  
            default:  
                this.message = 'huh?' 
                break;  
        }  
        println "${this.Capitalize(this.message)} ${this.Capitalize(name)}!"
    } 
}  

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor  
Greet g = new Greet()
// Call Setters  
g.setMessage('hello')
g.setName('world')
g.setLoopMessage(5)
// Call Method 2  
g.Salute()
// Overloaded Method 2.1 and Getters  
g.Salute(g.getMessage(), 'groovy', g.getLoopMessage()) 
// Overloaded Method 2.2  
g.Salute('carlos')

// Stop and exit  
println "Press any key to exit..."
Scanner sin = new Scanner(System.in)
String line = sin.nextLine()
sin.close()

Greetings Program - Minimal
// Groovy Basics
class Greet {
    // Fields or Attributes
    private def message
    private def name
    private def loopMessage    
    // Properties or Getters and Setters
    def getMessage() {  
        return message
    }  
    def setMessage(val) {  
        message = Capitalize(val)
    }  
    def getName() {  
        return name
    }  
    def setName(val) {  
        name = Capitalize(val) 
    }  
    def getLoopMessage() {  
        return loopMessage
    }  
    def setLoopMessage(val) {
        loopMessage = val
    }
    // Constructor  
    def Greet() {  
        message = ""
        name = ""
        loopMessage = 0
    }  
    // Overloaded Constructor  
    def Greet(message, name, loopMessage) {  
        this.message = Capitalize(message)
        this.name = Capitalize(name)
        this.loopMessage = loopMessage
    }
    // Method 1
    private def Capitalize(val) {  
        // "if-then-else" statement  
        if (val.size() >= 1) {  
            return val[0].toUpperCase() + val[1..-1]  
        }  
        else  {  
            return "";  
        }  
    }  
    // Method 2  
    def Salute() {  
        // "for" statement
        for (i in 1..loopMessage) {  
            println "$message $name!"  
        }  
    }  
    // Overloaded Method 2.1  
    def Salute(message, name, loopMessage) {  
        // "while" statement  
        def i = 0
        while(i < loopMessage) {  
            println "${Capitalize(message)} ${Capitalize(name)}!" 
            i++  
        }  
    }  
    // Overloaded Method 2.2  
    def Salute(name) {  
        // "switch/case" statement  
        def dtNow = new GregorianCalendar()
        switch (dtNow.get(Calendar.HOUR_OF_DAY))  
        {  
            case 6: case 7: case 8: case 9: case 10: case 11:  
                message = 'good morning,'
                break;  
            case 12: case 13: case 14: case 15: case 16: case 17:  
                message = 'good afternoon,' 
                break;  
            case 18: case 19: case 20: case 21: case 22:  
                message = 'good evening,' 
                break;  
            case 23: case 0: case 1: case 2: case 3: case 4: case 5:  
                message = 'good night,'
                break;  
            default:  
                message = 'huh?'
        }  
        println "${Capitalize(message)} ${Capitalize(name)}!"
    } 
}  

// Console Program
// Define variable object of type Greet and Instantiate. Call Constructor  
def g = new Greet()
// Call Setters  
g.setMessage('hello')
g.setName('world')
//g.setLoopMessage(5)
g.loopMessage = 5
// Call Method 2  
g.Salute()
// Overloaded Method 2.1 and Getters  
g.Salute(g.getMessage(), 'groovy', g.getLoopMessage())
// Overloaded Method 2.2  
g.Salute('carlos')

// Stop and exit  
println "Press any key to exit..."
def sin = new Scanner(System.in)
def line = sin.nextLine()
sin.close()


And the Output is:


















Auto-Implemented Properties in Groovy
Auto-implemented properties enable you to quickly specify a property of a class without having to write code to Get and Set the property. The following code shows how to use them just like with VB.NET, C#, C++/CLI and so on.

class Greet {  
    // Fields or Attributes
    // and Autoimplemented Properties (Getters and Setters)
    // To create auto implemented setters and getters you just define the fields with no explicit accessor
    String message = 'empty_message'
    def name = 'empty_name'
    Integer loopMessage = 0
    // if you specify an explicit accessor then you need to define your own explicit Setters and Getters
    // as I did in the minimal and verbose examples (because we needed the capitalize custom code in set properties)
    // Example:
    // public String message = 'empty_message'
    // private def name = 'empty_name'
    // protected Integer loopMessage = 0
    // The only one that will still create an auto-implemented Setter will be "final", but no setter since
    // that's how you do a read-only property.
    def Salute() {
        println "$message $name $loopMessage"
    }
} 
  

g = new Greet()
g.Salute()  
// Calling Auto-implemented Setters
g.setMessage('hello')
g.setName('world')
g.setLoopMessage(5)
g.Salute()  
// we can also access the fields from the class directly
g.message = 'bye'
g.name = 'carlos'
g.loopMessage = 2
// Calling Auto-implemented Getters
println g.getMessage() + ' ' + g.getName() + ' ' + g.getLoopMessage()


And the Output is: