Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using object functions in java

I'm trying to implement function objects in Java. I have a Unit class, with a default addition function that should be used in most initializations of a Unit object. However, for some issues, I need a different addition function. The code will look something like this:

public class Unit() {
   public Unit(unitType) {
      if (unitType == "specialType") {
         additionFunc = defaultFunc } else {
         additionFunc = specialFunc }
      }
   }
   public int swim() {
      return additionFunc()
   }
  // definiion of regularFunc
  // definition of specialFunc

}

Then, from the main file:

Unit fish = new Unit(regularTyoe);
Unit fatFish = new Unit(specialType);
fish.swim(); //regular function is called
fatFish.swim(); //special function is called

That's it.. does anyone know how this can be done?

like image 537
n00b programmer Avatar asked Jun 09 '26 10:06

n00b programmer


1 Answers

You need to look up inheritance and method overriding. It would probably help to read up on proper Object Oriented Programming as well.

The proper way to do this is:

class Fish {
  public void swim() {
    // normal swim
  }
}

class FatFish extends Fish {
  @Override
  public void swim() {
    // special swim
  }
}

Fish fish = new Fish()
Fish fatFish = new FatFish()
fish.swim()    // normal swim
fatFish.swim() // slow swim
like image 183
Reverend Gonzo Avatar answered Jun 11 '26 00:06

Reverend Gonzo