Search code examples
javaoopinheritanceconstructorsuperclass

Difference between super(variableName) ; and super.variableName


enter image description here What is the Difference between super(variable-name); and super.variableName = something; in a constructor, when you want to initialize the parameters and you wanna assign one of them to a variable of a parent class?

for example i want to implement the constructor of the "Zahnradfraese" and it takes the parameter "int Kennung" and this parameter should be assigned to the attribute "kennung" of the parent class "Produktionmittel"

Should I always use super when I wanna call a variable from this parent class or I just use it if I have another variable with the same name in the child class?


Solution

  • super(variable_name) represents a constructor call and should be first line in the constructor. Whereas super.variableName = something; means you are assigning a value to the instance variable of the parent class from the child class using super which is used to refer parent class objects.

    Now in your case: as per given class-diagram the class Zahnradfraese has a constructor which takes int Kennung argument. Also, kennung is the parent-class and has no constructor and instead it has method setKennung(). So you can do super.setKennung(kennung) from inside the constructor of Zahnradfraese class. You can also declare a constructor inside kennung but that would mean deviating from the class-diagram which has setter and getter methods and no constructor.

    public class Zahnradfraese extends Kennung{
      public Zahnradfraese(int kennung){
        super.setKennung(kennung);
      }
    }