Kotlin Class and Object
Kotlin Class and Object
Kotlin Class
Kotlin class is similar to Java class, a class is a blueprint for the objects which have
common properties. Kotlin classes are declared using keyword class. Kotlin class has
a class header which specifies its type parameters, constructor etc. and the class body
which is surrounded by curly braces.
1. class account {
2. var acc_no: Int = 0
3. var name: String? = null
4. var amount: Float = 0f
5.
6. fun deposit() {
7. //deposite code
8. }
9.
10. fun withdraw() {
11. // withdraw code
12. }
13.
14. fun checkBalance() {
15. //balance check code
16. }
17.
18. }
The account class has three properties acc_no, name, amount and three member
functions deposit(), withdraw(),checkBalance().
Pause
Unmute
Duration 4:57
Loaded: 100.00%
Â
Fullscreen
Kotlin Object
Object is real time entity or may be a logical entity which has state and behavior. It
has the characteristics:
Object is used to access the properties and member function of a class. Kotlin allows
to create multiple object of a class.
Create an object
Kotlin object is created in two steps, the first is to create reference and then create an
object.
1. obj.deopsit()
2. obj.name = Ajay
Let's create an example, which access the class property and member function using .
operator.
1. class Account {
2. var acc_no: Int = 0
3. var name: String = ""
4. var amount: Float = 0.toFloat()
5. fun insert(ac: Int,n: String, am: Float ) {
6. acc_no=ac
7. name=n
8. amount=am
9. println("Account no: ${acc_no} holder :${name} amount :${amount}")
10. }
11.
12. fun deposit() {
13. //deposite code
14. }
15.
16. fun withdraw() {
17. // withdraw code
18. }
19.
20. fun checkBalance() {
21. //balance check code
22. }
23.
24. }
25. fun main(args: Array<String>){
26. Account()
27. var acc= Account()
28. acc.insert(832345,"Ankit",1000f) //accessing member function
29. println("${acc.name}") //accessing class property
30. }
Output: