0

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?

dummydummy
  • 91
  • 1
  • 6
  • Check this out: https://stackoverflow.com/a/43510129/3780625 – Maxouille Mar 31 '21 at 21:08
  • 2
    Just pass the default value in a call from your child class constructor to the `super` (`Student`) constructor: `super(name, address, 25);` – GriffeyDog Mar 31 '21 at 21:14
  • @Maxouille No that is not quite a duplicate. This Questions adds the aspect of super class. – Basil Bourque Mar 31 '21 at 21:20
  • You should not use setter in the constructor. You can override that setter in a subclass to change its behavior. –  Mar 31 '21 at 23:08

1 Answers1

2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154