VSIP/formularium

Uit Wina Examenwiki
Naar navigatie springen Naar zoeken springen

Schrijf hier korte voorbeeldjes neer voor elke taal

Smalltalk

toewijzing :                   :=
null:                          nil
niet gelijk aan(pointer) :     ~~
this:                          self
locale variabele:              |localvar|
static:                        class
clone object o:                o copy
and:                           &

if statement

(cond)
      ifTrue: ['Auditorium: ' display.
               currentAuditorium getName displayNl.]
      ifFalse: ['Not in an Auditorium' displayNl.].

while

[cond] whileTrue: [C1]

array

newarray := Array new: 3.
newarray at: 1 put: 42.
^ newarray size

for

1 to: (newarray size) do:
  [:i| C1].

room.st

Object
       subclass: #Room
       instanceVariableNames:'name maxpopulation currentPopulation visitors'
       classVariableNames: 
       poolDictionaries: 	
!
!Room class methodsFor: 'construction'!
withName: theName andMaxPopulation: themaxpopulation
       |result|
       result := Room new.
       result withName: theName andMaxPopulation: themaxpopulation.
        ^result
!!
!Room methodsFor: 'Initialization'!
withName: theName andMaxPopulation: themaxpopulation
       name := theName.
       maxpopulation := themaxpopulation.
       currentPopulation := 0.
       visitors := Array new: maxpopulation.
!!

auditorium.st

Room
       subclass: #Auditorium
       instanceVariableNames:'resources'
       classVariableNames: 
       poolDictionaries: 	
!
!Auditorium class methodsFor: 'construction'!
withName: theName andMaxPopulation: themaxpopulation
       |result|
       result:= self new.
       result withName: theName andMaxPopulation: themaxpopulation.
       ^result
!!

main.st

FileStream fileIn: 'room.st'!
FileStream fileIn: 'auditorium.st'!
Smalltalk at: #a1 put: (Auditorium withName: '200A' andMaxPopulation: 5)!

Ideas: Everything is an object. To achieve something, you send messages to those objects. There are only messages and objects. Each variable can contain any object. There can be exceptions when messages are not understood. = dynamic type system. Everything is reference semantics. (dus ook integers etc) Alle small-integers met gelijke waarde zijn pointer gelijk, zelfde voor String literals. String literals ook immutable. 3 types message: unary (1 paramater nl receiver bv getName), keyword (meerde parameters bv put: at: ) of binary (+) Geen ondersteuning voor specificaties. Variables (class of instance) niet publiek Messages altijd publiek Klassen zijn ook objecten: instantiatie van de metaclass. Metaclasses zijn instanties van Metaclass klasse.

Eiffel

toewijzing :          :=
niet gelijk aan :     \=
null:                 Void  
string:               STRING
int:                  INTEGER     
this:                 Current  
return value:         Result
if cond then C1 else C2 end
class
  NEWCLASS                            -- de naam van je klasse
creation
  constructormethod                   -- constructoren aanduiden
feature{}                             -- globale variabelen      
  name:STRING
feature{}                             -- private other: feature{ANY}, feature{NAMECLASS1,NAMECLASS2}
  constructormethod(newname: like name) is       
  do                                  -- start method
     name :=  newname                 -- do stuff
  end                                 -- end constructor
feature{ANY}    
   -- OPMERKING: de volgende inspector functie moet eigenlijk niet meer gespecifieerd worden want deze is impliciet gegeven bij de declaratie van de variabele 'name'.
   get_name :STRING is                 -- get_name method (NAMING CONVENTIONS: get_name) 
      do                               --start method
           Result := name              --return name
      end                              --end method    
invariant
   valid_name : not Current.name.is_equal("")
end                                   -- end class NEWCLASS

Bij overerving: alle klassen worden overgeerfd (ook constructor). Afscherming kan veranderen met feature. Maar geen private, als een klasse toegang heeft dan hebben ook alle subklassen toegang. Attributen worden overgeërfd en zijn toegankelijk van subklasse. Redefine clause om nieuwe implementatie aan methodes te geven. Rename om ze te hernoemen. Bestaande precondities mogen versoepeld worden, postcondities verstrengd. Deferred classes = abstract classes in java. Deferred methodes = abstract methodes. Multiple inheritance: Inherit all variables from all parents. Same name variables are shared (joined)- different name replicated Inherit all functions from parents: to remove ambiguity: -Select clause in header: -Renaming methods in header: -undefine clause in header -deferred implementation

inherit FRENCH_DRIVER select address, violation_count, new_violation end

inherit FRENCH_DRIVER select all -- alle ambigue features end


overerving voorbeeld

class
       AUDITORIUM
inherit
       ROOM	
            rename build as build_room end  -- redefine parent method
      
creation
        build
feature{}
        build(n: like name; p: INTEGER) is -- (arg :like var) or (arg : TYPE) 
        do
               build_room(n, p) -- constructor parent classe aanroepe		
       end
end

Eiffel’s belangrijkste bijdrage :!! pre-condities !! post-condities!! class invariants!! check instruction Everything’s an object: Alles binnen klasse architectuur: Bovenste ANY, onderste NONE. Object semantiek: programmeur beslist: reference is standaard. Expanded maakt value semantiek. Ook mogelijk tot expanded variables voor gebruiker. Bij vergelijking reference semantiek => pointer gelijkheid, value semantiek (expanded) => value gelijkheid. Geen klass attributes. Geen overloading. Afscherming met feature{} blokken: Enkel toegankelijk maken voor niets of alles of bepaalde klassen. Precondities: requires clause. Post condities : ensure clause. Geen groepering in packages: programmeeromgeving beslist => klassen in .e files en een root object om te starten (constructor zonder paramaters).

C++

toewijzing :  =
null : 0

Superklasse:

#include "room.h" //naam van je header file

Room::Room(string theName, int theMaxPop)       //constructor
	:name(theName), maxPop(theMaxPop),currentPop(0){
	Person* population[maxPop];
}
Room::~Room(){           //destructor
	int count;
	for(count=0; count < maxPop; count=count+1){ //if constructie
		if(population[count]){
			population[count]->kickFromRoom();	//methodes bij reference semantic oproepen met ->
		}
	}
}


for constructie:

		for(count=0; count < maxPop; count=count+1){ 
			if(population[count] == 0 && !found){ 
				population[count] = p;
				found = true;
				p->incrementBudget(getVisitBudgetBonus());  
			}
		}

overerving:

Auditorium::Auditorium(string theName, int theMaxPop, bool hasResources)
	:Room(theName,theMaxPop),resources(hasResources){ //superconstructor direct oproepen.
	
} 

Explicite upcast:

Downcast: statisch "static_cast<Square *>(rect);", dynamisch, reinterpret cast of type conversion "Square *sq = (Square *)(rect);"


Multiple inheritance:

struct Car {
 virtual void Sell ();
};
struct House {
 virtual void Sell ();
};
struct MotorHome : Car , House {
 virtual void Sell ();
};

C#

The Basics

NOOT C# is, tenzij expliciet vermeld, identiek aan Java qua syntax

Main method
static void Main(string[] args) { ... }
Preprocessor
#if, #elif, #else. #endif
#define, #undef
Access control
  • Classes: public, internal (assembly; default)
  • Class members/structured types: public, internal, private (default), protected, protected internal
Variable number of parameters
public void myMethod(string a, params int[] a) { ... }
Foreach
MoneyAmount[] amounts = ...;
foreach (MoneyAmount thisAmount in amounts)
 thisAmount. ...
Enumerations
enum Day : int { Monday, ..., Friday = 5, ... };
Operators
public static MyType operator+(MyType l, MyType r) { ... return resultMyType; }
Casting
  • Square sq = (Square)rect;
  • if (box is int) a = 5 * ((int)box);
  • Square sq = rect as Square;
Properties
  • Getter/setter BEIDE publiek:
public string Foo { get; set; }
  • Alternatief (cfr. Java)
private string foo;
public string Foo {
  get { return foo; }
  set { foo = value; } }
Indexers
class A {
 int[,] myInts = int[8,8];
 A this[int row, int col] get { return myInts[row, col]; } set { myInts[row, col] = value; } }
class B {
 void Bla(A myA, int row, int col) { return myA[row, col]; } }
Constructor
  • readonly var initialization only within constructor
public class/struct Location {
 int x, int y;
 readonly string name;
 public Location(int x, int y) { this.x = x; this.y = y; name = "Sven"; }
 public Location(int x) : this(x, 0) {} }
Destructor
public class Location { ~Location() { ... } }

Inheritance

Interfaces
interface IMyInterface { void MyMethod(int a); }
class MyDefaultImpl : IComparable, IMyInterface { public void MyMethod(int a) { ... } ... }
Abstract
abstract public class A {
	abstract public int MethodA(); 
	public int MetodB() { ... } }
public class B : A {
	override public int MethodA() { ... } }
Sealed
public class A {
    public int MethodA() { ... } }
public class B : A {
    public sealed override int MethodA() { ... } }
public sealed class C : B { }
Extension Inheritance
public class Rectangle  {
	public Rectangle(int width, int height) { ... }
	public Foo(int a) { ... } }
public class PositionedRectangle : Rectangle {
	public PositionedRectangle(int x, int y, int width, int height) : base(width, height) { ... }
	new public Foo(int a) { ... }
	public Foo(string a) { ... } }
Specialization Inheritance
  • virtual methods: dynamic methods
public class Rectangle {
		public double Surface { ... }
		virtual public double Perimeter { ... } }
public class Square : Rectangle {
		new public double Surface { ... }
		override public double Perimeter { ... } }