Home > Software engineering >  Setter in parent class, with some child classes that don't have the parameter
Setter in parent class, with some child classes that don't have the parameter

Time:04-25

I was wondering what happens if you create a parent class with an empty setter method for a certain parameter, and then create a few classes that extend said class, but not all have the parameter. When calling the set method in a class where the parameter exists, it sets the param. And in classes where the parameter does not exist, nothing happens, for example:

class Parent{
    void setParam(String param){};
}

class A extends Parent{
    String param;
    public void setParam(String param){
        this.param = param;
    }
}

class B extends Parent{
    String otherParam;
    public void setOtherParam(String param){
        this.otherParam = param;
    }
}

so if we create class A, up cast it to Parent, and try setParam(), the property param will be set.

Parent parent = new A();
parent.setParam("PARAM");

A{param='PARAM'}

and if we would do the same with class B and try to setParam() nothing would happen.

Can someone explain what is happening 'under the hood'? I would expect to get an exception since I'm trying to set a parameter that does not exist.

CodePudding user response:

class A has overriden the method setParam of class Parent. Even though you assign A instance as Parent class, call on a.setParam() still behave as subclass A. That's what called "subclass polymorphism".

class B overrides nothing of parent. So b.setParam() just the call b's parent's setParam method, and nothing happen.

CodePudding user response:

In Parent class, setParam() is an empty method and calling it from any child class won't execute any line of code, unless the child class overrides it and adds a few lines of code to it.

Class A overrides setParam() and adds a line of code to it. Class B on the other hand doesn't override this method. So, when setParam() is called on an instance of A, the overridden method of A is executed and assigns the supplied value to the member variable param; however, when called on an instance of B, the method of Parent is executed and nothing happens because it is empty in Parent.

So, nothing is happening 'under the hood' in this case.

  • Related