First draft of OOP
This commit is contained in:
parent
e6c76be576
commit
ed5148d7e6
2 changed files with 41 additions and 1 deletions
40
content/oop.md
Normal file
40
content/oop.md
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
---
|
||||
title: Object Oriented Programming
|
||||
---
|
||||
|
||||
# Object Oriented Programming
|
||||
|
||||
Object oriented programming is supported through inheritance and `methods`, which are virtual procedures. Methods work in the same was as procs, but when an method is called with an object, the method that is actually run is resolved at runtime and depends on the type of the object.
|
||||
|
||||
Inheritance is created with the `of` keyword in the type declaration of an object. A method is overridden by creating a new method with parameter types of the subtype.
|
||||
|
||||
``` nimrod
|
||||
type Animal = ref object of TObject
|
||||
name: string
|
||||
age: int
|
||||
method vocalize(this: Animal): string = "..."
|
||||
method ageHumanYrs(this: Animal): int = this.age
|
||||
|
||||
type Dog = ref object of Animal
|
||||
method vocalize(this: Dog): string = "woof"
|
||||
method ageHummanYrs(this: Dog): int = this.age * 7
|
||||
|
||||
type Cat = ref object of Animal
|
||||
method vocalize(this: Cat): string = "meow"
|
||||
|
||||
|
||||
var animals: seq[Animal] = @[]
|
||||
animals.add(Dog(name: "Sparky", age: 10))
|
||||
animals.add(Cat(name: "Mitten", age: 10))
|
||||
|
||||
for a in animals:
|
||||
echo a.vocalize()
|
||||
echo a.age_human_yrs()
|
||||
```
|
||||
``` console
|
||||
$ nimrod c -r oop.nim
|
||||
woof
|
||||
10
|
||||
meow
|
||||
10
|
||||
```
|
||||
|
|
@ -9,7 +9,7 @@
|
|||
* [Case Statements](/case/)
|
||||
* [For Loops & Iterators](/for_iterators/)
|
||||
* [Procs](/procs/)
|
||||
* [Object Oriented Programming](/methods/)
|
||||
* [Object Oriented Programming](/oop/)
|
||||
* [First Class Functions](/procvars/)
|
||||
* [Blocks](/block/)
|
||||
* [Primitive Types](/primitives/)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue