Classes

From Rosetta Code
Task
Classes
You are encouraged to solve this task according to the task description, using any language you may know.

The purpose of this task is to create a basic class with a method, a constructor, an instance variable and how to instantiate it.

C++

Compiler: GCC 4.0.2

 class MyClass
 {
 public:
   void someMethod(); // member function = method
   MyClass(); // constructor
 private:
   int variable; // member variable = instance variable
 };
 
 // implementation of constructor
 MyClass::MyClass():
   variable(0)
 {
   // here could be more code
 }
 
 // implementation of member function
 void MyClass::someMethod()
 {
   variable = 1; // alternatively: this->variable = 1
 }
 
 // Create an instance as variable
 MyClass instance;
 
 // Create an instance on free store
 MyClass* pInstance = new MyClass;
 // Instances allocated with new must be explicitly destroyed when not needed any more:
 delete pInstance;

Note: MyClass instance(); would not define an instance, but declare a function returning an instance. Accidentally declaring functions when object definitions are wanted is a rather common bug in C++.

Functions can also be defined inline:

 class MyClass
 {
 public:
   MyClass(): variable(0) {}
   void someMethod() { variable = 1; }
 private:
   int variable;
 };

Note that member functions in C++ by default are not polymorphic; if you want a polymorphic member function, you have to mark it as virtual. In that case, you should also add a virtual destructor, even if that is empty. Example:

 class MyClass
 {
 public:
   virtual void someMethod(); // this is polymorphic
   virtual ~MyClass(); // destructor
 };

Objective-C

Compiler: GCC 4.0.1 (apple)

The declaration:

@interface MyClass : NSObject
{
    /* member variables */
    int variable;
}

/* method declarations */
- init;
- (void)someMethod;

@end

The implementation:

@implementation MyClass
/* method implementations */

- init    /* designated constructor */
{
    if (self = [super init])
        variable = 0;
    return self;
}

- (void)someMethod
{
    variable = 1;
}

@end

A C function that uses the class:

void example()
{
    MyClass *mc = [[MyClass alloc] init];
    [mc someMethod];
    [mc release];	/* explicitly decrement reference count */
}


Forth

Declare a class

:class MyClass <super Object

  int memvar

  :m ClassInit: ( -- )
       ClassInit: super
       1 to memvar ;m

  :m ~: ( -- )  ." Final " show: [ Self ] ;m

  :m set: ( n -- )  to memvar ;m
  :m show: ( -- ) ." Memvar = " memvar . ;m

;class

Allocate a static object

MyClass newInstance

Allocate a dynamic object, saving its pointer in a global variable.

New> MyClass  value newInstance

Call member functions

10 set: newInstance
show: newInstance

Free a dynamically allocated object

newInstance dispose
0 to newInstance   \ no dangling pointers!

Example of dynamic allocation and local variable use"

: test { \ obj -- }
    New> MyClass to obj
      show: obj
      1000 set: obj
    obj dispose ;

Java

Platform: J2SE/

 public class MyClass {
 
   // instance variable
   private int variable;  // Note: instance variables are usually "private"
 
   /**
   * The constructor
   */
   public MyClass() {
     // creates a new instance
   }
 
   /**
   * A method
   */
   public void someMethod() {
    this.variable = 1; // Note: "this." is optional
                       // variable = 1; works also
   }
 }

JavaScript

Interpreter: Firefox 2.0

//constructor
function MyClass(initVal) {
    //instance variable
    if(initVal == undefined) {
        this.number = 1;
    }
    else {
        this.number = initVal;
    }
}

//method of MyClass
MyClass.prototype.getDouble = function() {
    return this.number * 2;
};

var instance1 = new MyClass; //or "new MyClass();"
instance1.number = 5;
alert( instance1.getDouble() ); //10

var instance2 = new MyClass(3);
alert( instance2.getDouble() ); //6

Oberon-2

Compiler: OO2C 2.1.11

MODULE M;

   TYPE
      T = POINTER TO TDesc;
      TDesc = RECORD
         x: INTEGER
      END;

   PROCEDURE New*(): T;
      VAR t: T;
   BEGIN
      NEW(t); t.x := 0;
      RETURN t
   END New;


   PROCEDURE (t: T) Increment*;
   BEGIN
      INC(t.x)
   END Increment;

END M.

Exported procedures are marked with an asterisk (*). There is nothing special about the constructor New, it is just a function that returns a new object of type T. The name of the method receiver can also be chosen freely. INC is a predeclared procedure that increments its argument.

Perl

Interpreter: perl 5.8.6

The implementation (there are no declarations):

{
     # a class is a package (i.e. a namespace) with methods in it
    package MyClass;

     # a class method is a function that takes a class name as itself.
     # a constructor is a class method that returns a blessed object.
    sub new {
        my ($class) = @_;
        bless {variable => 0}, $class
         # the instance object is a hash in disguise.
         # (it can be any primitive type.)
    }

     # an instance method is a function that takes an object as itself.
    sub someMethod {
        my ($self) = @_;
        $$self{variable} = 1;
    }
}

Using the class:

$instance = new MyClass;      # indirect object syntax
$instance2 = MyClass->new;    # method syntax

$instance->someMethod;
 # instance deallocates when the last reference falls out of scope

Python

Interpreter: Python 2.5

class MyClass:
    name2 = 2 # Class attribute

    def __init__(self):
        """
        Constructor
        """
        self.name1 = 0 # Instance attribute
  
    def someMethod(self):
        """
        Method
        """
        self.name1 = 1
        MyClass.name2 = 3
  
  
myclass = MyClass()

for new-style classes (correct me if i'm wrong), in order to make good use of properties, class methods and the like :

class MyClass(object):
    ...

Ruby

class MyClass
  @@classVar
  def initialize
    @instanceVar = 0
  end
  def someMethod
    @instanceVar = 1
    @@classVar = 3
  end
end
myclass = MyClass.new