Reputation: 2609
I have just started programming in Kotlin, and have come through inheriting classes and defining derived classes in two ways.
1.
open class Derived (var a: String="") : Base()
open class Derived : Base() {
var a: String=""
}
The Base class being this:
open clas Base( var x: String="")
My code works fine in both the cases, however, I wanted to understand if there's any difference in both the styles or is there something I am totally missing.
Upvotes: 0
Views: 153
Reputation: 31
The first case you are passing a parameter a: String=""
with a default value of empty.
The second case you are defining the string inside the class.
So it's about who knows the information.
If the class itself don't have the information, the first case will be used,
i.e. the class is dependent on ourside scope because it knows nothing about the information a
Btw, naming variables that you can understand easily helps a lot in long run. Please avoid using variable name like a
for most cases.
Upvotes: 1
Reputation: 7882
It has nothing to do with inheritance. It's just two ways of declaring class properties.The difference is that in the first case you not just declare a property, but also allow to initialize it in primary constructor. So you may instantiate Derived
like this:
val derived = Derived("123") //works only in first case
which is equivalent to:
//works in both cases
val derived = Derived()
derived.a = "123"
Upvotes: 3