thp-web/md/learn/classes/definition.md

95 lines
1.1 KiB
Markdown
Raw Normal View History

2023-10-02 01:41:38 +00:00
# Classes
Basically kotlin syntax.
Methods have to have a first parameter `$`.
## Create a new instance of a class
`new` not required, in fact, forbidden.
```thp
val dog = Dog()
```
## Simple class
Why'd you do this tho?
```thp
class SimpleClass
val instance = SimpleClass()
```
## Properties & methods
```thp
class SimpleClass
{
// Properties are private by default
var String? name;
2023-10-24 01:39:34 +00:00
// Made public with `pub`
pub var String? surname;
2023-10-02 01:41:38 +00:00
// Methods are private by default
fun display_name($)
{
// `$` is used instead of $this
print($name)
}
2023-10-24 01:39:34 +00:00
pub fun get_name($) -> String?
2023-10-02 01:41:38 +00:00
{
$name
}
}
```
## Static members
no
## Constructor
Kotlin style
```thp
class Cat(val String name)
{
2023-10-24 01:39:34 +00:00
pub fun get_name($) -> String
2023-10-02 01:41:38 +00:00
{
$name
}
}
val michifu = Cat("Michifu")
print(michifu.get_name())
```
## Inheritance
Kotlin style
```thp
class Animal(val String name)
{
2023-10-24 01:39:34 +00:00
pub fun say_name($)
2023-10-02 01:41:38 +00:00
{
print($name)
}
}
class Cat(String name, Int lives) -> Animal(name)
Cat("Michi", 9).say_name()
```