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

bookCreating and Using Objects

Scorri per mostrare il menu

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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 3
some-alt