Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Creating and Using Objects | Introduction to Classes and Objects
Kotlin Classes and Objects

bookCreating and Using Objects

Veeg om het menu te tonen

Instantiating Objects

In Kotlin, a class acts as a blueprint for creating objects. When you define a class, you are describing the structure and behavior that its objects will have, but no actual object exists until you create one. Instantiating an object means making an instance of a class in memory so you can use it in your program.

To create an object, you use the class name followed by parentheses. This calls the class's constructor, which sets up the object. Once you have an object, you can work with its properties and functions.

Accessing Objects

After you instantiate an object, you can access its properties and methods using the dot (.) operator. This allows you to get or set property values, or call functions defined in the class.

StudentExample.kt

StudentExample.kt

copy

In the code above, you define a Student class with two properties: name and age. The line val student = Student("Alice", 20) creates an object of type Student by calling the constructor with the values "Alice" and 20. This object is stored in the variable student. You can then access the name and age properties of the student object using student.name and student.age, which are printed to the console.

question mark

How do you create an object from a class in Kotlin?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 1. Hoofdstuk 3
some-alt