Home > front end >  Subclass Parameter Name Overriding Superclass Val
Subclass Parameter Name Overriding Superclass Val

Time:02-01

Experienced with Java, but fairly new to Kotlin.

When the subclass param has same name as a superclass val... Android Studio does not throw validation error stating need for @Override annotation. However, attempting to access name from within Business references the param name rather than the superclass val (which feels like an override to me).

class Business(
    val name: String
) {
    // ...
}

class FirstBusiness(name: String) : Business(name) {
    val test = name; // name referencing param name rather than super's name
}

Of course, I can just name the param something different, but I really just want to pass the name to the superclass... otherwise excluding any storage of it in FirstBusiness.

Am I overlooking something? I'm surprised that even if I don't declare FirstBusiness param name as a val/var, it seems to be overriding Business.name. I'm assuming the param isn't truly overriding the super val as the IDE isn't complaining... but why is the param the only suggestion instead of the super val?

Edit: I do notice different (more expected from my Java experience) behavior if I do the param-passing outside of the primary constructor design like so...

class FirstBusiness : Business {
    constructor(name: String) : super(name)

    fun thing() {
        val v = name // now references super's name
    }
}

Thank you!

CodePudding user response:

Just like how you would do it in Java if you have shadowed the name of a superclass's field, you can clarify it with the super keyword.

class FirstBusiness(name: String) : Business(name) {
    val test = super.name
}

In your case, it's not overriding the superclass's property. What's happening is that property initializers at the property declaration sites are considered part of the primary constructor's initialization block, so the constructor parameter is closer in scope than the superclass's property.

Suppose for a moment that these classes were defined in Java, and in the superclass you simply used a field instead of a getter:

public class Business {
    public String name;

    public Business(String name) {
        this.name = name;
    }
}

Then your code where you initialize your property at its declaration site is just like initializing a field from a constructor, like this in Java:

public class FirstBusiness extends Business {
    private String test;

    public FirstBusiness(String name) {
        super(name);
        this.test = name; // It's using the parameter, not the superclass's 
                          // property, but the superclass property isn't overridden.
    }
}
  •  Tags:  
  • Related