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

bookCreating and Using Objects

Sveip for å vise menyen

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?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 3
some-alt