Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Defining Classes in Kotlin | Classes
Practice
Projects
Quizzes & Challenges
Quiz
Challenges
/
Introduction to Kotlin

bookDefining Classes in Kotlin

Scorri per mostrare il menu

In Kotlin, a class is a blueprint for creating objects that encapsulate data and behavior. Classes allow you to group related properties and functions together, making your code organized and reusable. To declare a class, use the class keyword followed by the class name and curly braces. Once a class is defined, you can create objects (instances) of that class using the class name as a constructor.

Below is a simple example that demonstrates how to declare a class and create an object in Kotlin.

Main.kt

Main.kt

copy
12345678910111213
package com.example class Person { var name: String = "" var age: Int = 0 } fun main() { val person = Person() person.name = "Alice" person.age = 30 println("Name: ${person.name}, Age: ${person.age}") }

In this example, the Person class is defined with two properties: name and age. Both properties have default values. The main function creates an object of the Person class using val person = Person(). The object's properties are then assigned values, and their values are printed using string interpolation. This demonstrates how you can define a class, instantiate it, and access or modify its properties in Kotlin.

question mark

Which of the following correctly declares a class and creates an object in Kotlin?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 1

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 4. Capitolo 1
some-alt