简体   繁体   中英

inheritance and constructors for the super class

when i puts an arrow between super class and a child class it prompt: no suitable constructor found (for the super class object. in this case for Date inside Person).

what the story of constructors and inheritance? why does a super class need a constructor in a child class?

here the constructors of the super class:

public class Date
{
    protected int _day;
    protected int _month;
    protected int _year;
    public final int MAX_DAY = 31;
    public final int MIN_DAY = 1;
    public final int MAX_MONTH = 12;
    public final int MIN_MONTH = 1;
    public final int DEFUALT_YEAR = 4;

    public Date (int day, int month, int year)
    {
      if( (MIN_DAY <= day) && (day <= MAX_DAY) && (MIN_MONTH <= month) 
      && (month <= MAX_MONTH) && (year == DEFUALT_YEAR))
      {
        this._day = day;
        this._month = month;
        this._year = year;
      }
      else
      {
        this._day = 1;
        this._month = 1;
        this._year = 2000;
      }
    }

    public Date (Date other)
    {
        _day = other._day;
        _month = other._month;
        _year = other._year; 
    } 

here the constructors of the child class:

public class Person extends Date
{
   private String _first;
   private String _last;
   private long _id;
   private Date _date;

   public Person (String first, String last, long id, int d, int m, int y)
   {
     this._first = first;
     this._last = last;
     this._id = id;
     Date _date = new Date(d, m, y); 
    }

    public Person (Person other)
    {
     this._first = other._first;
     this._last = other._last;
     this._id = other._id;
     this._date = other._date;
    }

You would need to call super() to make the constructors compatible Eg.

public class Person extends Date
{
   private String _first;
   private String _last;
   private long _id;
   // private Date _date; Lose the Date as every property of date is accessible here

   public Person (String first, String last, long id, int d, int m, int y)
   {
     super(d, m, y)
     this._first = first;
     this._last = last;
     this._id = id;
    }

    public Person (Person other)
    {
     this._first = other._first;
     this._last = other._last;
     this._id = other._id;
     this._day = other._day;
     this._month = other._month;
     this._year = other._year;
    }
 ...
 }

Ref: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

Ref: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM