// Define a class called Person
class Person(val name: String, val age: Int) {
// Define a method called speak
fun speak() {
println("Hello, my name is $name and I am $age years old.")
}
}
fun main() {
// Create an instance of the Person class
val person = Person("John", 25)
// Call the speak method on the person instance
person.speak()
}
// Define a simple class called Car
class Car {
// Properties
var color: String = "Red"
var model: String = "XYZ"
// Method
fun startEngine() {
println("Engine started")
}
}
fun main() {
// Create an instance of the Car class
val myCar = Car()
// Accessing object properties
println("My car's color is ${myCar.color}")
println("My car's model is ${myCar.model}")
// Calling a method on the object
myCar.startEngine()
}
// Define a class called Dog
class Dog {
// Properties
var breed: String = "Labrador"
var age: Int = 3
// Method
fun bark() {
println("Woof! Woof!")
}
}
fun main() {
// Create an instance of the Dog class
val myDog = Dog()
// Accessing object properties
println("My dog's breed is ${myDog.breed}")
println("My dog's age is ${myDog.age}")
// Calling a method on the object
myDog.bark()
}
// Define a class using encapsulation to protect internal state
class Person {
// Private data fields
private var name: String = "John"
private var age: Int = 30
// Getter methods to access private data fields
fun getName(): String {
return name
}
fun getAge(): Int {
return age
}
// Setter methods to modify private data fields
fun setName(newName: String) {
name = newName
}
fun setAge(newAge: Int) {
if (newAge > 0) {
age = newAge
}
}
}
fun main() {
// Create an instance of the Person class