Java: possible to call up a function with unknown parameters

3041 views java
3

in a theoretical view how would the function "absSensor" in the class "sensorFinal" be able to call the function "proximitySensorAdjusted" in the class "proximitySensor" IF the class "sensorFinal" does not have access to the integer "value"?

Is there a standard way to call functions in which access to data is limited or is there a workaround? Thanks in advance!

public class proximitySensor
{
    double adjustment = 5;
    public double proximitySensorAdjusted(int value)
    {
        double finalValue = value + adjustment;
        return finalValue; 
    }
}

public class sensorFinal
{
    public double absSensor()
    {
        proximitySensor sensorValue = new proximitySensor();
        sensorValue.proximitySensorAdjusted( ??? ) 
    }
}

answered question

3 Answers

12

Instead of ??? you need to specify any integer value for example 0 or 5. In your example int value is an argument name. Only code inside that function has access to it.

posted this
2

You can use method overloading.

public double proximitySensorAdjusted(int value) {
    double finalValue;
    if(value == -1) {
        finalValue = adjustment;
    } else {
        finalValue = value + adjustment;
    }
    return finalValue;
}

public double proximitySensorAdjusted() {
    return proximitySensorAdjusted(-1); //call with some default value
}

Now you can call sensorValue.proximitySensorAdjusted();.

posted this
10

In java you are allowed to create functions with the same name, but different parameters.

So a better solution is to declare a proximitySensorAdjusted in your proximitySensor class which takes no arguments

public class proximitySensor {

    double adjustment = 5;
    public double proximitySensorAdjusted(int value) {
        double finalValue = value + adjustment;
        return finalValue; 
    }

    public double proximitySensorAdjusted() {
        ... // Do something intelligent here
    }
}

As a sidenote, the naming convention for class names in Java is Capitalized, so your proximitySensor class should be called ProximitySensor.

posted this

Have an answer?

JD

Please login first before posting an answer.