1

For an assignment I have to write code for a "State" class that has all the attributes about position of an airplane.

The Javadoc is already written up and must be strictly adhered to. All the set methods are public but must throw an exception if any class other than Airplane try to use them.

I can't change the structure of either class at all or the visibility. My professor said to use either a "clone" or a boolean somehow. How would I go about doing this?

public void setSpeed(double speed)
{
    if(method called by any class other than Airplane.java)
    {
        //throw exception
    }
    else
    {
        //continue setting speed
    }
}
SpencerJL
  • 203
  • 1
  • 2
  • 8

2 Answers2

2

I agree that this requirement is nonsense but this could do it:

public void setSpeed(double speed)
{
   if(!Airplane.class.equals(Thread.getCurrentThread().getStacktrace()[1].getClass()))
   {
    //throw exception
Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
0

Since these are non-static methods, we can use getClass() to check who called the method and compare it with the Airplane.class. The getStackTrace() technique is great, but not needed here. Also we should use != instead of equals(Object) because we want to check the actual class and not allow a situation where the implementation of Airplane.equals(Object) does not check sub-classes.

public void something() {
    if (Airplane.class != getClass()) {
        throw new IllegalArgumentException("Cannot call from " + getClass());
    }
    // and so on...
}
pamcevoy
  • 1,136
  • 11
  • 15
  • Nope, this does not work. This only fails, if the object is a subclass of `Airpane`. Furthermore whether an exception is thrown is completely independent from the calling class. E.g. `new Airpane().something()` doesn't throw an exception no matter where it's called. – fabian Oct 18 '16 at 13:50
  • Ah good point. I'll have to think a bit more. – pamcevoy Oct 18 '16 at 23:07