Classes
Creating a class
Defining the class
You can easily define a class using this simple syntax
Adding fields
Fields are variables that can be accessed from any functions of the class, but also externally from other functions that have access to the specific classes instance.
Fields are defined using a simple name: type;
assignment. You can not set a default value, unless you do it from the constructor.
Adding methods
Methods are functions inside the class. All methods have access to an argument named this
which is the specific instance of the class, that the method is being called on.
Methods are defined the same way as normal functions. There is no need to add the this
argument manually.
Adding a constructor
A constructor is a special method that is called when the class is initialized. The method name has to be constructor
.
A class doesn't have to have a constructor. When a new instance of a class is created, if it doesn't have a constructor, all fields will be initialized with null values.
Using a class
Creating a new instance
To create a new instance of a class, simply use the new ClassName()
expression, supplying any arguments necessary. You can store this new instance in a variable with the classes data type.
Accessing fields
Any fields of a method can be externally accessed and both read and written to.
Calling methods
Methods are called similairly as in other languages
Last updated