Object-oriented Programming (OOP): In object-oriented style of programming, you can divide a complex problem into smaller sets by creating objects.
These objects share two characteristics:
- state
- behavior
Let's take example:
1. Fan is an object
o It can be in on or off state.
o You can turn on and turn off Fan(behavior).
Class: A class is a blueprint for the object.We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows etc. Based on these descriptions we build the house. House is the object.
Since, many houses can be made from the same description, we can create many objects from a class.
Classes in Kotlin are declared using the keyword class:
class ClassName {
// property
// member function
... .. ...
}
Example:
class Fan{
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
}
Here, we defined a class named Fan .
The class has one property isOn (defined in same way as variable), and two member functions turnOn() and turnOff().
Kotlin Objects
When class is defined, only the specification for the object is defined; no memory or storage is allocated.
To access members defined within the class, you need to create objects. Let's create objects of Fan class.
class Fan{
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
}
fun main(args: Array<String>) {
val f1 = Fan() // create f1 object of Fan class
val f2 = Fan() // create f2 object of Fan class
}
This program creates two objects f1 and f2 of class Fan. The isOn property for both fans f1 and f2 will be false.
How to access members?
You can access properties and member functions of a class by using .(dot) notation. For example,
f1.turnOn()
This statement calls turnOn() function for f1 object.
Example: Kotlin Class and Object
class Fan{
// property (data member)
private var isOn: Boolean = false
// member function
fun turnOn() {
isOn = true
}
// member function
fun turnOff() {
isOn = false
}
fun displayStatus(fan: String) {
if (isOn == true)
println("$fan Fan is on.")
else
println("$fan Fan is off.")
}
}
fun main(args: Array<String>) {
val f1 = Fan() // create f1 object of Fan class
val f2 = Fan() // create f2 object of Fan class
f1.turnOn()
f2.turnOff()
f1.displayStatus("f1")
f2.displayStatus("f2")
}
When you run the program, the output will be:
f1 Fan is on.
f2 Fan is off.
No comments:
Post a Comment