Passing a method to another method from a different Class - java

Basically im coding a differential equation solver class that will take equations from an "Equation" Class and solve it using the rK4 method.
The main problem Im running into, is that I can't find a way to send a method to another class without extending and gaining acess through inheritance, or making a specefic instance of that Equation methods in my ODE class.
for example, how would I make the code below work? (remember I am not allowed to make a specific instance of Equation methods within the ODE class):
public class Equations {
public double pressureDrp( double a, double b) {
return a+b; //this is just a dummy equation for the sake of the question
}
public double waffles( double a, double b) {
return a-b; //this is just a dummy equation for the sake of the question
}
}
public class ODE {
//x being a method being passed in of "Equations" type.
public double rK4( Equation method x ) {
return x(3, 4);
//this would return a value of 7 from the pressureDrp method in class Pressure
//if I had passed in the waffles method instead I would of gotten a value of -1.
}
}

I would use an interface to encapsulate the concept of a binary method and to allow call-backs, something like:
interface BinaryEquation {
double operate(double d1, double d2);
}
This could then be placed in your equations class like so:
class Equations {
public static class PressureDrop implements BinaryEquation {
#Override
public double operate(double d1, double d2) {
return d1 + d2;
}
}
public static class Waffles implements BinaryEquation {
#Override
public double operate(double d1, double d2) {
return d1 - d2;
}
}
}
And used like so:
class ODE {
public double rk4(BinaryEquation eq) {
return eq.operate(3, 4);
}
}
Or better like so:
public class BinaryTest {
public static void main(String[] args) {
System.out.println("PressureDrop(3, 4): " + new Equations.PressureDrop().operate(3, 4));
System.out.println("PressureDrop(3, 4): " + new Equations.Waffles().operate(3, 4));
}
}

Related

Java Overridden method visibility scope

How is the following program correct?
abstract class Calculate
{
abstract int multiply(int a, int b);
}
public class Main
{
public static void main(String[] args)
{
int result = new Calculate()
{
#Override
int multiply(int a, int b)
{
return a*b;
}
}.multiply(12,32);
System.out.println("result = "+result);
}
}
We are changing the scope of the overridden method here.It is not public anymore and it should of default scope.Is the scope change of overridden method allowed?
You are creating an anonymous subclass in your current code, but you are very close to having a functional interface. Let's change it to that, like
#FunctionalInterface
interface Calculate {
int multiply(int a, int b);
}
Now you have a single abstract method and can use fancy lambdas. Like,
public static void main(String[] args) {
Calculate calc = (a, b) -> a * b;
int result = calc.multiply(12, 32);
System.out.println("result = " + result);
}
Note this is exactly like your original example, just syntactic sugar added with Java 8.
From your code, it multiply is not public to begin with. If you change your mulyiply method your Calculate class to
public abstract int multiply(int a, int b);
then it will not work.
According to your code, the calculate method is not in public scope, so you are not changing the scope.
abstract class Calculate {
public abstract int multiply(int a, int b);
}
public class MyClass {
public static void main(String[] args) {
int result = new Calculate() {
#Override
public int multiply(int a, int b) {
return a * b;
}
}.multiply(11,11);
System.out.println("result = " + result);
}
}
The access level cannot be more restrictive than the overridden method's access level. For example: If the super class method is declared public then the overriding method in the subclass cannot be either private or protected.
Now there is a separate scope as default scope introduced in java , so you can call it as package private scope.
For rules of overriding in java you can follow the Link

Java how to make a method argument accept subclass type and superclass

I have a superclass and one subclass with some variables like below:
public class A{
private int first;
private int second;
public A(int _first, int _second){
first = _first;
second = _second;
}
public int getFirst(){
return first;
}
}
public class B extends A{
private int third;
public B(int _first, int _second, int _third){
super(_first, _second);
third = _third;
}
public int getThird(){
return third;
}
}
I want to build a method in the main class that accepts a generic argument that can be of type A or type B like below:
public class Main{
public int val = 2;
public static void main(String []args){
A a = new A(1, 2);
B b = new B(1, 2, 3);
printObject(a);
printObject(b);
}
public void printObject(A a){
int f = a.getFirst() * val;
int s = a.getSecond() * val;
if(a instanceOf B){
int t = a.getThird() * val; // compiler does not find the getThird() method this way
}
}
}
How can this be achieved?. is generics an option? I have thought about making printObject() method inside A then override it inside B however I have some other variable like val above that I am creating in main.
update
I tried to use instanceOf like the above method. But this way the compiler does not find the subclass's specific method.
Firstly, by definition, if you declare A as a parameter to any method and B is it's sub-class, then any A or B can be passed to that method.
You could then achieve what you want using the instanceof operator (to check if the parameter passed in is of type B). However, inheritance / method override should typically be used rather than instanceof.
You could pass 'val' into the printObject() methods on A/B. If several variables like 'val' are involved you could pass in another object or perhaps you need to split your code across multiple methods on class A (overridden in B), passing in different values as appropriate? (You wouldn't normally do calculations in a method whose purpose is to print an object but perhaps that was just an example?)
Everything is much simplier) You could get rid of this method in the main class, cause it's producing some redundant coupling. And all this instanceof really smells in 2019. You could make it more independent.
Class A:
public class A{
private int first;
private int second;
public A(int _first, int _second){
first = _first;
second = _second;
}
public int getFirst(){
return this.first;
}
public int getSecond(){
return this.second;
}
public void print(int multiplier) {
System.out.println(this.first * multiplier);
System.out.println(this.second * multiplier);
}
}
Class B:
public class B{
private int third;
public B(int _first, int _second, int _third){
super(_first, _second);
third = _third;
}
public int getThird(){
return this.third;
}
#Override
public void print(int multiplier) {
super.print(multiplier);
System.out.println(this.third * multiplier);
}
}
Class Main:
public class Main{
public int val = 2;
public static void main(String []args){
A a = new A(1, 2);
B b = new B(1, 2, 3);
a.print(val);
b.print(val);
}
}
Writing object oriented code is more than extending a class , your API's and other functionality should be designed as part of the solution.
In your case, the most appropriate way to do this is to add the print method to the object itself, you can either override the entire function or to call the super class inside the overriding class.
public class A{
/// ... your code
public void print(){
System.out.println("first :"+first+", second : "+second);
}
}
public class B extends A{
/// ... your code
public void print(){
//Option A - use parent class getters/setters to implement print for object B
System.out.println("first :"+super.getFirst()+", second : "+super.getsecond() +" third" + third);
}
//Option B (More usable to methods returning a value or performing an update) - Perform operation on parent variables, then perform on class specific variables
super.print()
System.out.println("third : "+third);
}
}
and then
A a = new A();
A b = new B();
a.print();
b.print();
Will each call the correct runtime function based on their actual implementation

Array of methods: Adapter Pattern?

Problem Description:
I want to be able to pass around a list of methods to other classes where the methods have been defined in only one class. If the methods, some of which have input parameters and non-void return types, are defined in one class, I want to be able to pass a list of some of them, with possible duplicates, as a parameter to some other class's constructor.
Code Description:
The code below is a crude example and can be ignored if it detracts from the main goal. Another example, in addition to the one below, would be a case where the methods are int Add(int n1, int n2), int Subtract(int n1, int n2), Multiply, etc.. and the interface has a method called int MathOperation(int n1, int n2).
Attempt to solve the problem:
The adapter pattern seems to have the functionality I'm looking for but I have only seen examples where the methods in the interface have no input or output parameters. An example implementation I wrote just for this question is posted below.
Problem Analogy:
You have a random picture generator web service. There are 30 mutations that can be applied to an image. The client connects and clicks a "generate" button and a random list of some of those functions are passed to some other class within the web service which then proceeds to run those functions with it's own data while also collecting and possibly re-using the return values to generate some mutated cat image. It can't just explicitly call the methods in the other class because that process needs to be done randomly at run-time. That is why I lean towards the idea of generating a random list of methods which are executed in-order when the 'generate' button is clicked.
I hope I have been clear.
public class SomeClass {
...
public double UseWrench(double torque, boolean clockwise) { ... }
public double UsePliers(double torque, boolean clockwise) { ... }
public double UseScrewDriver(double torque, boolean clockwise) { ... }
public boolean UseWireCutters(double torque) { ... }
interface IToolActions {
double TurnFastener(double torque, boolean clockwise);
boolean CutWire(double torque);
}
private IToolActions[] toolActions = new IToolActions[] {
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseWrench(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UsePliers(double torque, boolean clockwise); } },
new IToolActions() { public double TurnFastener(double torque, boolean clockwise) { double UseScrewDriver(double torque, boolean clockwise); } },
new IToolActions() { public boolean CutWire(double torque) { boolean UseWireCutters(double torque); } },
};
}
public class Worker<T> {
public List<? extends IToolActions> toolActions;
public Worker(List<? extends IToolActions> initialToolSet){
toolActions = initialToolActions;
}
}
While #alainlompo has the general idea, Java 8 simplifies this greatly by using something such as BiConsumer (for doubles) or even just a Consumer for the class object. In fact, you can go really crazy, and have a method accept varargs lambdas:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
}
public class Worker {
#SafeVarargs
public Worker(SomeClass example, Consumer<? extends SomeClass>... operations) {
for (Consumer bc : operations) {
bc.accept(example);
}
}
}
Then, this is easily simplified:
SomeClass c = new SomeClass();
new Worker(c, SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
While it seems a little awkward applying it like that (due to it being an Adapter pattern), you can easily see how this could apply to a class body:
public class SomeClass
public double useWrench(double torque, boolean clockwise) { ... }
public double usePliers(double torque, boolean clockwise) { ... }
public double useScrewDriver(double torque, boolean clockwise) { ... }
public boolean useWireCutters(double torque) { ... }
#SafeVarargs
public void operate(Consumer<? extends SomeClass>... operations) {
for (Consumer<? extends SomeClass> bc : operations) {
bc.accept(example);
}
}
}
//Elsewheres
SomeClass c = new SomeClass();
c.operate(SomeClass::useWrench, SomeClass:usePliers, SomeClass::useScrewDriver, SomeClass::useWireCutters);
Of course, you don't need varargs, it will work just as well simply passing a Collection
But wait there's more!!!
If you wanted a result, you can even use a self-returning method via a Function, e.g.:
public class SomeClass {
public double chanceOfSuccess(Function<? super SomeClass, ? extends Double> modifier) {
double back = /* some pre-determined result */;
return modifier.apply(back); //apply our external modifier
}
}
//With our old 'c'
double odds = c.chanceOfSuccess(d -> d * 2); //twice as likely!
There's so much more flexibility provided from the Function API in java 8, making complex problems like this incredibly simplified to write.
#John here is how I have approached a solution to your problem.
I used the case of MathOperations to make it simpler. I think first that I would be better to have the interface outside of SomeClass like:
public interface MathOperable {
public int mathOperation(int n1, int n2);
}
I created two examples of classes implementing this interface and one anonymous implementation inside SomeClass (I did an Add, Multiply and an anonymous "Substract")
public class Add implements MathOperable {
public int mathOperation(int n1, int n2) {
return n1 + n2;
}
public String toString() {
return "<addition>";
}
}
The overriding of toString() is simply for the purpose of giving more readability to the examples that I will show at the end of my post.
public class Multiply implements MathOperable {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1 * n2;
}
public String toString() {
return "<multiplication>";
}
}
Here is my SomeClass class, it contans a getRandomListOfOperations, where I simulate what happens when the click on the button is done
public class SomeClass {
private static MathOperable addition = new Add();
private static MathOperable multiplication = new Multiply();
// Anonymous substraction
private static MathOperable substraction = new MathOperable() {
public int mathOperation(int n1, int n2) {
// TODO Auto-generated method stub
return n1-n2;
}
public String toString() {
return "<substraction>";
}
};
public List<MathOperable> getRandomListOfOperations() {
// We put the methods in an array so that we can pick them up later randomly
MathOperable[] methods = new MathOperable[] {addition, multiplication, substraction};
Random r = new Random();
// Since duplication is possible whe randomly generate the number of methods to send
// among three so if numberOfMethods > 3 we are sure there will be duplicates
int numberOfMethods = r.nextInt(10);
List<MathOperable> methodsList = new ArrayList<MathOperable>();
// We pick randomly the methods with duplicates
for (int i = 0; i < numberOfMethods; i++) {
methodsList.add(methods[r.nextInt(3)]);
}
return methodsList;
}
public void contactSomeOtherClass() {
new SomeOtherClass(getRandomListOfOperations());
}
}
Now here is my SomeOtherClass (which may correspond to your Worker class)
public class SomeOtherClass<T extends MathOperable> {
Random r = new Random();
List<T> operations;
public SomeOtherClass(List<T> operations) {
this.operations = operations;
runIt();
}
public void runIt() {
if (null == operations) {
return;
}
// Let's imagine for example that the new result is taken as operand1 for the next operation
int result = 0;
// Here are examples of the web service own datas
int n10 = r.nextInt(100);
int n20 = r.nextInt(100);
for (int i = 0; i < operations.size(); i++) {
if (i == 0) {
result = operations.get(i).mathOperation(n10, n20);
System.out.println("Result for operation N " + i + " = " + result);
} else {
// Now let's imagine another data from the web service operated with the previous result
int n2 = r.nextInt(100);
result = operations.get(i).mathOperation(result, n2);
System.out.println("Current result for operation N " + i + " which is " + operations.get(i) +" = " + result);
}
}
}
}
I have a simple test class that contains a main to connect the two classes
public class SomeTestClass {
public static void main(String[] args) {
SomeClass classe = new SomeClass();
classe.contactSomeOtherClass();
}
}
Now a few examples of executions:
And another illustration!
I hope this could be helpful!
Okay, I'm going to be "that guy"... the one who understands the question but asks anyway to restate the problem because I think you are on the wrong path. So, bear with me: if you like what you see, great; if not, I understand.
Basically, you have a different intent/motivation/purpose than what "adapter" is suited for. The command pattern is a better fit.
But first, more generally, one of the goals of designing "elements of reusable software" (from the title of the original GOF design patterns book) is that you don't want to modify code when you add functionality; rather, you want to add code without touching existing functionality. So, when you have:
public class Toolbox {
public void hammer() { ... }
}
and you want to add a screwdriver to your toolbox, this is bad:
public class Toolbox {
public void hammer() { ... }
public void screwdriver() { ... }
}
Rather, ideally, all existing code would remain unchanged and you would just add a new Screwdriver compilation unit (i.e., add a new file), and a unit test, and then test the existing code for regression (which should be unlikely, since none of the existing code changed). For example:
public class Toolbox {
public void useTool(Tool t) { t.execute(); ...etc... }
}
public interface Tool { // this is the Command interface
public void execute() // no args (see ctors)
}
public Hammer implements Tool {
public Hammer(Nail nail, Thing t) // args!
public void execute() { nail.into(t); ... }
}
public Screwdriver implements Tool {
public Screwdriver(Screw s, Thing t)
public void execute() { screw.into(t); ... }
}
Hopefully it should become clear how to extend this to your example. The Worker becomes straight-foward list of Tools (or, for clarity, instead of "Tool" , just call it a "Command").
public class Worker {
public List<Command> actionList;
....
public void work() {
for(...) {
action.execute();
}
}
}
This pattern also allows for easy "undo" functionality and "retry", as well as memoization (caching results so they don't have to be re-run).

Java Overloading: Number,Number ; int,Double

In two days i have an exam in java, and i can not figure out the answer to this question:
class ClassA {
public String foo(Integer x , int y) {
return "Integer, int";
}
public String foo(int x, Double y) {
return "int, Double";
}
public String foo(Number x, Number y) {
return "Number, Number";
}
public String foo(Object x, Object y) {
return "Object, Object";
}
public static void main(String... args) {
ClassA a = new ClassA();
System.out.print(a.foo(5, 1.2f) + " ");
System.out.println(a.foo(null, null));
}
}
What's the output?
The Answer is:
Number, Number Number, Number
I know that java always chooses the most specified Method, that is why a.foo(null,null); will envoke the Number,Number Method and not the Object,Object Method.
But why does a.foo(5,1.2f); also envoke the Number,Number Method and not the int,Double Method??
But one more thing which might be helpful:
If i remove the f after 1.2, so that the call is:
a.foo(5,1.2);
I get a compiler error, that it can not choose between the Number,Number and int,Double Method...
Would be really helpful, if you guys could explain that to me :)
1.2f is not wrapped by a Double, it's wrapped by a Float. SinceFloat is not a subclass of Double (they are distinct subclasses of Number), the most specific method signature that can be used is foo(Number,Number).
Once you remove the f, 1.2 will be treated a double (the primitive, not the wrapper class) by default, which can be autoboxed to a Double. However the 5 can also be autoboxed to an Integer, thus causing the ambiguity.
There are two important factors here.
First, 1.2f is not a Double. It's a Float. The (int, Double) function doesn't match at all. (Number, Number) is the best fit.
Second, even when you change it to 1.2 it is still not a Double. It is a double. That is, it's a primitive, not an object. Now, Java will still happily pass a double into a function that wants a Double without much complaint, but in this case you've confused it by giving it two valid conversions it could make:
Convert 5 to an Integer and convert 1.2 to a Double
Leave 5 as a primitive int but convert 1.2 to a Double.
There isn't a rule for which of those is preferable. Java produces a compiler error that it has an ambiguous function call, and forces you to choose which one you'd prefer (by manually wrapping one or both of them in objects).
As an aside, if you had a method that took (int, double) there would be no ambiguity at all: that method actually matches the existing types of 5 and 1.2, so it would be called. It's the fact that some of the arguments here are wrapper objects that causes the mayhem.
Generic Answer:
public class OverloadingNumeric {
public void print(int x){
System.out.println("int");
}
public void print(long x){
System.out.println("long");
}
public void print(float x){
System.out.println("float");
}
public void print(double x){
System.out.println("double");
}
public void print(Integer x){
System.out.println("Integer");
}
public void print(Long x){
System.out.println("Long");
}
public void print(Float x){
System.out.println("Float");
}
public void print(Double x){
System.out.println("Double");
}
public void print(Number x){
System.out.println("Double");
}
public void print(Object x){
System.out.println("Object");
}
public static void main(String[] args) {
OverloadingNumeric obj = new OverloadingNumeric();
/*
* Primitives will take more precedence
* of calling instead of wrapper class arguments,
*/
obj.print(10);
obj.print(10l);
obj.print(10f);
obj.print(10d);
obj.print(10.1);
//obj.print(999999999999999); Error: this letral type int is out of range
obj.print(999999999999999l);
/*
* OUTPUT
* int
* long
* float
* double
* double
* long
*/
/*
* Assume all primitive argument methods
* are commented. then calling the same again
*/
obj.print(10);
obj.print(10l);
obj.print(10f);
obj.print(10d);
obj.print(10.1);
//obj.print((Double)10); //Cannot cast int to Double
obj.print((double)10); //Success
//obj.print((Float)10); //Cannot cast int to Float
obj.print((float)10); //Success
//obj.print(null); ERROR AMBIGUOUS
/*
* OUTPUT
* Integer
* Long
* Float
* Double
* Double
* Double
* Float
*
*/
}
}
interface SuperIfc {}
class SuperClass implements SuperIfc{}
class SubClass extends SuperClass {}
public class OverloadingTest {
public void print(SuperIfc x){
System.out.println("SuperIfc");
}
public void print(SuperClass x){
System.out.println("SuperClass");
}
public void print(SubClass x){
System.out.println("SubClass");
}
public void print(Object x){
System.out.println("Object");
}
public static void main(String[] args) {
OverloadingTest obj = new OverloadingTest();
SuperClass superObj = new SuperClass();
SubClass subObj = new SubClass();
obj.print(superObj);
obj.print(subObj);
obj.print(null);
obj.print((SuperIfc)superObj);
obj.print((SuperIfc)subObj);
obj.print((SuperIfc)null);
/*
* OUTPUT
* SuperClass
* SubClass
* SubClass
* SuperIfc
* SuperIfc
* SuperIfc
*/
}
}

Java - implementation instances inside an interface

In my project I need to create objects for each kind of Java Math Operator like "Add", "Substraction", "Multiplication", etc. And these operators should be singletons.
So here is what I am going to do. I define the Math Operator as an interface and I put those implementations inside it as I don't want to define singleton classes for each operator.
public interface MathOperator {
double operate(double a, double b);
MathOperator ADD = new MathOperator(){
#Override
public double operate(double a, double b) {
return a + b;
}
};
MathOperator SUBSTRACT = new MathOperator(){
#Override
public double operate(double a, double b) {
return a - b;
}
};
}
I don't see much of such usage when I Google this. So I wonder if this is a good practice and if there are better and more graceful approaches?
I would do smt like
1) Define interface
interface MathOperator {
double operate(double a, double b);
}
2) Than have some common implementation in enum (less code)
enum MathOperators implements MathOperator {
ADD {
#Override
public double operate(double a, double b) {
return a + b;
}
},
SUBTRACT {
#Override
public double operate(double a, double b) {
return a - b;
}
}
}
3) Or public static members (more clean solution).
class MathOperators {
public static MathOperator ADD = new MathOperator() {
#Override
public double operate(double a, double b) {
return a + b;
}
};
public static MathOperator SUBTRACT = new MathOperator() {
#Override
public double operate(double a, double b) {
return a - b;
}
};
}
can create new MathOperator without changing MathOperators
have nice API for common operations
shouldn't write singletons
have nice clean interface
One idiom that I've seen used in precisely these circumstances is the use of enum:
public enum MathOperator {
ADD {
#Override
public double operate(double a, double b) {
return a + b;
}
},
SUBTRACT {
#Override
public double operate(double a, double b) {
return a - b;
}
};
public abstract double operate(double a, double b);
}
I use this pattern often, especially for specific implementations of generic interfaces. I find it works really well for me.
I like the way it puts the implementations where you can find them. I do it slightly differently - I make them static (it's a style thing, so the interface impls look more like class impls):
public interface MathOperator {
double operate(double a, double b);
public static MathOperator ADD = new MathOperator() {
#Override
public double operate(double a, double b) {
return a + b;
}
};
public static MathOperator SUBSTRACT = new MathOperator() {
#Override
public double operate(double a, double b) {
return a - b;
}
};
}
I don't see any problem with it. Take java.lang.String.CASE_INSENSITIVE_ORDER for instance. It is almost the same, except that
String is not an interface but a final class
The Comparator is not declared using an anonymous class, but using a static inner class, which is essentially the same
Personally, I don't like putting implementations within interfaces. I would either:
make MathOperator an enum
keep the interface but have a factory or a static class (say MathOperators) with the implementations
Why don't you define each implementation in its own class/file? This would make it clearer and would leave the interface clean.

Categories

Resources