简体   繁体   中英

Proper syntax for super()?

When I use super() to use a superclass method, what is the proper way to return?

Let's say I have a class Hourly. It contains a constructor also called Hourly that has parameters "String name" and "double rate. The UML version looks like:

+Hourly(name:String, rate:double)

However, the "name" variable is a private attribute of the Employee class, of which the class hourly is related to via inheritance. By this I mean that the UML show a clear arrow (not a diamond) going from the class Hourly and pointing to the class Employee.

How would I write the constructor Hourly???

I have a basic skeleton of:

public Hourly(String name, double rate){


}

Please help me fill it in.

On a separate note, let's say that there was a return in a method. Say I wanted to return the double rate . What would be the proper syntax to return some that uses super() as I know I couldn't simply use:

return this.rate;

Your Employee surely has a name.

private String name;

public Employee(String name) {
    this.name = name;
}

Following that, your Hourly must also have a name. Since an Hourly is-an Employee , you must set the name on it as well. That is accomplished like so.

public Hourly(String name, double rate) {
    super(name);
    this.rate = rate;
}

According to your comments, name is stored by the superclass; rate is not. So you should store rate in the Hourly class you're defining, while passing name to the super constructor, as follows:

public class Hourly {

  private double rate;

  public Hourly(String name, double rate) {
    super(name);
    this.rate = rate;
  }

  public double getRate() {
    return rate;
  }
}

If Hourly is sub class of Employee and if you want to parse the name to super class (Employee) then in your Hourly constructor call super(name);

public Hourly(String name, double rate){
    super(name);
}

Since Hourly extends Employee :

    class Hourly extends Employee {

    private int rate;

    public Hourly(String name, int rate) {
      super(name);  //assuming Employee has this constructor
      this.rate = rate;
    }

    //this make sense if name is protected and doesn't have getter in base class
    //ideally you would have this in base class itself
    public String getName() {
       return super.name; //for rate there is no sense in using super as it is not known to super 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