Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
abstract class Base
{
public static boolean IsValueCorrect( int value )
{
value = preSetup( value ); // Call static function that must be defined in derived class.
// Do some common work here.
value = postSetup( value ); // Call static function that must be defined in derived class.
return (value == 0);
}
protected abstract static int preSetup( int value );
protected abstract static int postSetup( int value );
...
}
public class Derived1 extends Base
{
protected static int preSetup( int value )
{
// No pre-setup needed for Derived1.
return value;
}
protected static int postSetup( int value )
{
// No post-setup needed for Derived1.
return value;
}
...
}
public class Derived2 extends Base
{
protected static int preSetup( int value )
{
if ( value < 0 )
{
throw new InvalidArgumentException( "Value cannot be negative!" );
}
return value;
}
protected static int postSetup( int value )
{
if ( (value == 2) || (value == 13) )
{
value = 0;
}
return value;
}
...
}
But then I'd need an object instance to call the virtual function. Since the work the function is doing has nothing to do with the state of the object, ideally it should be static.uolj said:you can call a regular (virtual) non-static method that can either do the work or call another static function from that class.
if (Derived1.isValueCorrect (42) && Derived2.isValueCorrect (-7))
// ...
class Derived3 extends Base
{
private int lower, int upper;
public Derived (int lower, int upper)
{
this.lower = lower;
this.upper = upper;
}
public int postSetup (int value)
{
if ((value > lower) && (value <= upper))
// ...
interface PreSetup { int preSetup (int value);}
interface PostSetup { int postSetup (int value);}
interface PrePostSetup extends PreSetup, PostSetup {}
final class Base
{
public static boolean isValueCorrect (PrePostSetup pps, int value)
{
value = pps.preSetup (value);
// Do some common work here.
value = pps.postSetup (value);
return (value == 0);
}
}
final class Derived1 implements PrePostSetup
{
public int preSetup (int value)
{
return something;
}
public int postSetup (int value)
{
return somethingElse;
}
}
public class BddTest
{
public static void main (String args [])
{
PrePostSetup d1 = new Derived1 ();
PrePostSetup d2 = new Derived2 ();
System.out.println (Base.isValueCorrect (d1, 7));
System.out.println (Base.isValueCorrect (d2, 7));
System.out.println (Base.isValueCorrect (d1, -42));
System.out.println (Base.isValueCorrect (d2, -42));
}
}