The soccer ball has 2 function to represent the bound and roll behavior of a soccer ball. It also have a property call diameter that tells you the length of the ball.
Classes in Kotlin has a primary constructor and may have one or more secondary constructors. They are used to set variables and execute logic before an instance of the object is actually created..
Classes in Kotlin has a primary constructor and may have one or more secondary constructors. They are used to set variables and execute code before the object is actually created.
Classes in Kotlin has a primary constructor and may have one or more secondary constructors. They are similar to a functions with parameters.
Syntax
Creating an Instance
To create an instance of an object using a Class is the same as calling a function.
val earthObject = Earth()
In the above code, we created an Earth object and stored it in a variable call earthObject. This way, we can reference the object and access it's properties and functions.
earthObject.spin()
Here, we called the spin() function.
Constructors
Classes in Kotlin has a primary constructor and may have one or more secondary constructors. They are used to set the values of variables and execute logic before the object is actually created.
Syntax
Primary Constructor
Secondary Constructor
Primary Constructor
The Primary Constructor is located after the class name in the Class header.
In the example, there is a class call Earth with a Primary Constructor. Similar to calling a function with parameters, when we create an object with a class that has a constructor that contains parameters, we need to pass in the value.
val littleEarth = Earth(100)
Variables that are placed in the primary constructors are also properties that we can access inside the class or outside.
val population = littleEarth.population
Primary Constructors does not allow you to execute logic. In order to perform logic, you need to add Initializer Blocks inside the class definition using the init keyword.
Secondary Constructors
Secondary Constructors are located inside the class definition using the "constructor" keyword.
In the example, there is a Class call Earth with a empty primary constructor and a secondary constructor with a parameter call life.
Since there are multiple constructors, as long as we fulfil the need of at least one of them, we can create an object.
val littleEarth = Earth()
val oldEarth = Earth(200)
Both statements are valid.
If the class have a Primary Constructor, all the secondary constructor must be combined with the primary constructor.
In the above example, the Earth class now has a parameter in the Primary Constructor. The secondary constructor needs to contain the same parameter(s) that the primary constructor have.and more. Then after the parenthesis, you need to add a colon, then "this," and then pass in the necessary values.