Properties and Methods
Scorri per mostrare il menu
When you define a class in Kotlin, you can give it properties and methods. Properties are variables that hold data about each object created from the class. Methods are functions that describe what the object can do. By combining properties and methods, you can model real-world things and their behaviors in your code.
Person.kt
1234567891011121314151617package com.example class Person { var name: String = "" var age: Int = 0 fun greet() { println("Hello, my name is $name and I am $age years old.") } } fun main() { val person = Person() person.name = "Alice" person.age = 28 person.greet() }
In this example, the Person class has two properties: name and age. These properties store information about each Person object. The greet method is a function inside the class that prints a message using the properties. When you create a new Person and assign values to name and age, you can call greet() to see a personalized greeting. You access properties with dot notation, like person.name, and call methods the same way, like person.greet().
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione