简体   繁体   中英

Inheritance Best Practice Java

Say I have a parent class Emitter, with attributes

private double launchAngle;
private double launchAngleVariation;

and a constructor

public Emitter(double launchAngle, double launchAngleVariation)
{ this.launchAngle = launchAngle;
  this.launchAngleVariation = launchAngleVariation;
}

and a child class MobileEmitter, with attribute

private int a;

and a constructor

public MobileEmitter(double launchAngle, int a)
{ super();   //how should this be handled?
  this.a = a;}

My question is what is the best way to handle the super call?

Should I create an empty constructor in the parent class and make launchAngle protected so that I can assign the value directly in the child constructor?

Or is it better practice to create a separate constructor in the parent class with just launchAngle as a parameter then call super(launchAngle) ?

private int a;

public MobileEmitter(double launchAngle, double launchAngleVariation, int a) {
    super(launchAngle, launchAngleVariation);
    this.a = a;
}

This is what I think you would need. The super call must have the some values assigned to it. In your case you are calling the default constructor found in the Emitter class ( parent class ).

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