Search code examples
javaimplementationfinal

Setting final value in a constructor


I have the following problem. I have two classes - one is the base class and the pther is inheriting it. So in the parent class is an abstract class and it consists three fields - String name, String adress and int age. However in my task it says the value for age has to be set by default to be 25 years. My question is - How do implement this value with the help of inherited method setAge() in the constructor of the inherited class? My abstract constructor looks like this:

public Student(String name, String adress, int age){
    this.setName(name);
    this.setAdress(adress);
    this.setAge(age);
}

and setter:

public void setAge(int age){
    this.age = age;
}

How do I do the implementation in the inherited class by using a default value?


Solution

  • If the superclass constructor takes three parameters in its constructor, and you have subclass with a constructor with only two parameters, you can call super to pass the two arguments plus a third default value to the constructor of the superclass.

    public abstract class Person
    {
        // Constructor
        public Person() ( String name, String address, int age ) 
        { …
    

    And subclass.

    public abstract class Student
    {
        // Constructor
        public Person() ( String name, String address ) 
        { 
            super( name , address , 25 ) ;  // Default age of 25 for new `Student` objects.
            …
    

    This is a silly example as defaulting a person’s age would not happen in real work. But the concepts demonstrated are sound.