0

I discovered that both constructor parameters and member variables behave almost the same way.

The only difference is that: the noOfSides cannot be changed inside class Square, whereas noOfSideVar can be changed inside the class Square

Code that I have written:

fun main(args: Array<String>) {
    var square1 = Square(4)
    println("Parameter form: ${square1.noOfSides}")
    println("Variable form: ${square1.noOfSideVar}")

    square1.noOfSides = 10
    square1.noOfSideVar = 50

    println("New Parameter form: ${square1.noOfSides}")
    println("New Variable form: ${square1.noOfSideVar}")

}

open class Polygon(var noOfSides: Int)

class Square(noOfSides: Int) : Polygon(noOfSides) {

    var noOfSideVar = 7
    fun area(): Int {
        return noOfSides * noOfSides
    }

}

The output of the above code:

Parameter form: 4
Variable form: 7
New Parameter form: 10
New Variable form: 50

Process finished with exit code 0

If I am having any sort of misconception, please clear it. I know this is a fundamental question but I am quite confused as a beginner.

  • Are you aware that when printing `println("Parameter form: ${square1.noOfSides}")`, you are not actually accessing the constructor parameter (it is impossible to do that from `main`)? You're just accessing the member variable `noOfSides` that `Square` inherits from `Polygon`. – Sweeper Aug 29 '21 at 06:34
  • @Sweeper `noOfSides` is a parameter for `Polygon` . So, I think I am accessing the **inherited parameter**. What do you say about this? Please point out where I am going wrong. –  Aug 29 '21 at 06:37
  • It is a parameter for `Polygon`, but it is _also_ a member variable (aka _property_). See that `var` prefix? Are you aware of what it means? – Sweeper Aug 29 '21 at 06:39
  • @Sweeper not have knowledge of that actually. SO what is the difference –  Aug 29 '21 at 06:40
  • The point is: both `noOfSides` and `noOfSideVar` in your example are member variables and this is why you don't see a difference between them. – broot Aug 29 '21 at 08:14
  • @broot What if I remove var/val which is before `noOfSides`. how will the code be affected? Also if you can classify what should I learn so that this confusion of mine no longer persists I would be grateful. @Sweeper –  Aug 29 '21 at 13:25
  • You can really check it by yourself. If you remove `var` then as a result you will remove `noOfSides` property and it won't be available in both `main()` and `area()` functions. This syntax is described here: https://kotlinlang.org/docs/classes.html#constructors , starting from: "Kotlin has a concise syntax for ..." – broot Aug 29 '21 at 17:41

0 Answers0