Question: How do I make the following corrections in the java program below? I must use Constructors, toString and equals methods. 1. The method withinRange could

How do I make the following corrections in the java program below? I must use Constructors, toString and equals methods.

1. The method withinRange could be simplified as follows:

public boolean withinRange(int distance) { return (distance <= this.getRange()); }

It takes the value of distance and compares it immediately with the value of the instance variable range, return the result of the comparison. The comparison gives an automatic boolean that can be used instead of creating separate values.

2. Notice in the simplification above that I used this.getRange() instead of using the direct name of the variable range. This is what encapsulation is all about. We shield the value of the variable range by calling using the get method and change its value with the set method. Doing that avoids mistakes in the future because it centralizes the access to the variable range thru these methods. You should do the same everywhere in your class. For example in the fly method you should use the set method to change the value of the distanceTravelled. The same may go for the assignments made in the Constructors.

public class Airplane

{

private String name;

private String model;

private int distanceTravelled;

private int range;

public Airplane()

{

}

public Airplane(String name, String model, int range)

{

this.name = name;

this.model = model;

this.distanceTravelled = 0;

this.range = range;

}

public void setName(String name)

{

this.name = name;

}

public void setModel(String model)

{

this.model = model;

}

public void setDistanceTravelled(int distanceTravelled)

{

this.distanceTravelled = distanceTravelled;

}

public void setRange(int range)

{

this.range = range;

}

public String getName()

{

return name;

}

public String getModel()

{

return model;

}

public int getDistanceTravelled()

{

return distanceTravelled;

}

public int getRange()

{

return range;

}

public void fly(int distance)

{

if(withinRange(distance))

{

distanceTravelled += distance;

}

else

{

System.out.println("Danger! " + getName() + " can't fly. Out of plane's range. ");

}

}

public boolean withinRange(int distance)

{

if(distance > range)

{

return false;

}

else

{

return true;

}

}

public String toString()

{

return "Name: " + getName() + " " +

"Model: " + getModel() + " " +

"Range: " + getRange() + " " +

"Distance Travelled: " + getDistanceTravelled() + " ";

}

} // end Airplane

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!