So I've seen, in many places, calling methods of a class like:
SomeClass obj = new SomeClass();
obj.addX(3).addY(4).setSomething("something").execute();
I don't think I completely understand how that works. Is each method independent of each other, so the above is equal to:
obj.addX(3);
obj.addY(4);
obj.addSomething("something");
obj.execute();
Or are they designing their class structure in some other fashion that allows for this. If they are how are they designing their classes to support this?
Also, does that have a specific name? Or is this just calling methods on a class?
That would be method chaining. It can do one of two things.
Each call to a method returns this which allows you to continue to call methods on the original instance.
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass addX(int n)
{
_x += n;
return this;
}
public SomeClass addY(int n)
{
_y += n;
return this;
}
public SomeClass setSomething(String something)
{
_something = something;
return this;
}
// And so on, and so on, and so on...
}
Each method call returns a new instance of the class with everything copied/updated appropriately. This makes the class immutable (so you don't accidentally modify something that you didn't mean to).
public class SomeClass
{
private int _x = 0;
private int _y = 0;
private String _something = "";
public SomeClass(int x, int y, String something)
{
_x = x;
_y = y;
_something = something;
}
public SomeClass addX(int n)
{
return new SomeClass(_x + n, _y, _something);
}
public SomeClass addY(int n)
{
return new SomeClass(_x, _y + n, _something);
}
public SomeClass setSomething(String something)
{
return new SomeClass(_x, _y, something);
}
// And so on, and so on, and so on...
}
Some people have also mentioned Fluent Interfaces. Fluent Interfaces utilize method chaining to create an API that provides something along the lines of a Domain Specific Language which can make code read much more clearly. In this case, your example doesn't quite qualify.
they modify object's state and return the same object back mostly
class Number{
int num;
public Number add(int number){
num+=number;
return this;
}
}
you can call it like
new Number().add(1).add(2);
most of the time the use case is to return new Object to support immutability
Each of those methods return an instance. For example, the call to
obj.addX(3)
will return the same instance obj, so the call
obj.addX(3).addY(4)
will be equivalent to
obj.addY(4)
This is called method chaining.
The methods are implemented like this:
public SomeClass addX(int i) {
// ...
return this; // returns the same instance
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 abc = new Test1();
abc.add1(10, 20).sub1(40, 30).mul1(23, 12).div1(12, 4);
}
public Test1 add1(int a, int b)
{
int c = a + b;
System.out.println("Freaking Addition output : "+c);
return this;
}
public Test1 sub1(int a, int b)
{
int c = a - b;
System.out.println("Freaking subtraction output : "+c);
return this;
}
public Test1 mul1(int a, int b)
{
int c = a * b;
System.out.println("Freaking multiplication output : "+c);
return this;
}
public Test1 div1(int a, int b)
{
int c = a / b;
System.out.println("Freaking divison output : "+c);
return this;
}
}
Related
Cheers, I am pretty new to java and I and I have ran across a problem
I have three classes, all inheriting things between them. Starting I have a class A:
public class A{
private int index;
public A(int index) {
System.out.println("Creating an instance of A");
this.index = index;
}
}
then I have a sublass of A, class M which has a enum inside as:
public class M extends A{
public enum Letter {
A,B,C;
}
private Letter letter;
public M(int index, Letter aLetter) {
super(index);
System.out.println("Creating an instance of M");
this.letter = aLetter;
}
}
and finally a last class P , subclass of M:
public class P extends M {
private T t;
public enum T{
o,
a,
t
}
public P(int index, Letter aLetter, T aT) {
super(index,aLetter);
System.out.println("Creating an instance of P");
this.t = aT;
}
}
What I want to do is create e.g. 3 objects of the class P, and pass on to them RANDOMLY a value of each of these enums. I thought of creating a function in the main class which would be kind of like:
Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
my main looks like this:
int N = 3;
M[] new_m = new M[N]
for(int i = 0; i < N; i++) {
new_m[i] = new P(i, getRandLetter(), getRandT());
}
however I get this error: Cannot make a static reference to the non-static method . What Can I do to achieve what I want?
The error is telling what to do:
Cannot make a static reference to the non-static method
Your main method is static, and the methods called from it should be static as well. So your getRandLetter() and getRandT() methods should be static.
getRandLetter() should look like this:
static Letter getRandLetter() {
Random rand = new Rand();
int pick = rand.nextInt(M.Letter.values().length);
if (pick == 0) {
return Letter.A;
} else if (pick == 1) {
return Letter.B;
} else {
return Letter.C;
}
}
And getRandT() should be static as well.
Let A be an interface which has a method a.
Let B be a class which implements A and has method a and has three fields 1,2,3.
I want to use two instances of A (meaning B), both of which have different values of 1,2,3 (present in cfg file) at two different places.
Can someone provide a simple and elegant solution to this problem using Guice.
You don't tell how the class that uses your dependency references the interface. I assume that you want to reference it with an interface.
What you can use, is annotation that will denote which instance you want to use. Assume that these are your implementations:
interface A {
void a();
}
class B implements A {
private int value;
void a() { ... }
B(int value) { this.value = value; }
}
And these are the classes that use the implementations:
class UserFirst {
private A a;
#Inject
UserFirst(#Named("first") A a) { this.a = a; }
}
class UserSecond {
private A a;
#Inject
UserSecond(#Named("second") A a) { this.a = a; }
}
The thing that decides which implementation is going to be injected is the #Named annotation. You can also define your annotations, but usually it's an overkill.
Now, in order to bind that, you can do something like this:
class MyModule extends AbstractModule {
#Override
protected void configure() {
A first = new B(1);
B second = new B(2);
bind(A.class)
.annotatedWith(Names.named("first")).toInstance(first);
bind(A.class)
.annotatedWith(Names.named("second")).toInstance(second);
}
}
Here's the full documentation: https://github.com/google/guice/wiki/BindingAnnotations
if I do understand you correctly, you might want to make B abstract so that you can override the methods which you want to change, if this is the case.
Now I can only assume that by fields you mean field-varriables. I would then recommend you to make them NON-static and change them in the constructor when you make an object. Then read the values of 1,2,3 in the public static void main method and send them upon creating a new object:
public class B implements A {
private int x,y,z;
/**
* This would now be the constructror
*/
public B(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
/**
* Then some return functions
*/
public get1() { return this.x; }
public get2() { return this.y; }
public get3() { return this.z; }
/**
* Then whatever methods you get from A
*/
public int someMethodFromA(int x, int y){
return x*y;
}
}
public static void main(String[] args) {
/**
* Some random method to read inn from CFG file
*/
int x1 = readXFromCFG();
int y1 = readYFromCFG();
int z1 = readZFromCFG();
B objectB1 = new B(x1,y1,z1);
int x2 = readXFromCFG();
int y2 = readYFromCFG();
int z2 = readZFromCFG();
B objectB2 = new B(x2,y2,z2);
int x3 = readXFromCFG();
int y3 = readYFromCFG();
int z3 = readZFromCFG();
B objectB3 = new B(x3,y3,z3);
}
When i call s1.dub(7) or s2.dub(7) it doesn't work
,but calling it with a string like s2.dub("9") works and prints the doubled string
Could any one tell me why?
Here's the code
interface Inter {
int number();
}
abstract class Abs {
static int foo = 12;
int number() { return 5; }
abstract int ace();
}
final class Sub extends Super {
Sub(int bar) { foo = bar; }
public int number() { return 10; }
int ace() { return 13; }
int dub(int i) { return 2 * i; }
}
public class Super extends Abs implements Inter {
public int number() { return 11; }
public static void main(String args[]) {
Super s1 = new Super();
Super s2 = new Sub(16);
//System.out.println(s1.dub(7)); //doesn't work
//System.out.println(s2.dub(7)); //doesn't work
//System.out.println(s1.dub("7")); //works giving 77
//System.out.println(s2.dub("7")); //works giving 77
}
int twice(int x) { return 2 * x; }
public int thrice(int x) { return 3 * x; }
int ace() { return 1; }
String dub(String s) { return s + s; }
}
Very easy.. you class Super defines a method:
String dub(String s) { return s + s; }
in your main method you instantiate Super:
Super s1 = new Super(); // this has a dub( String ) method
then you try to call this method (dub) passing a integer, instead of a string:
System.out.println(s1.dub(7)); // s1.dub(...) takes a String, not a number
EDIT: This code should not compile, or run, because you are assigning both instances to the super class Super (which does not define a dub(int) method).
Not sure how you are getting exceptions?
Thank you #Jean-FrançoisSavard - I totally missed that!
EDIT2: The original question was modified and no longer indicates that an exception is thrown, which makes sense as the code should not compile at all.
EDIT3: (last one, due to original question changing)
System.out.println(s1.dub(7)); //- this will never work unless you change your class' definition
System.out.println(s2.dub(7)); //- will work if you also change the following line:
from:
Super s2 = new Sub(16);
to:
Sub s2 = new Sub(16);
Imagine I have a class
class A {
int a;
int b;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
return 0;
}
void setTheFunction([...]) {
[...]
}
}
And for every new object I instantiate, I want to be able to define theFunction() in a new way by calling setTheFunction( [...] ). For example, I want to do something like this:
A test = new A(3,2);
test.setTheFunction ( int x = a*b; return x*x+2; );
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
Or something like this:
A test2 = new A(1,5);
test.setTheFunction ( for(int i=0; i<b; i++) a=a*b*i; return a; );
Now, what I could of course do is write all of those functions inside class A and use a switch statement to determine which one is to pick. But if I don't want the algorithm of theFunction() hardcoded inside my class A, is there any way to do something similar to the above? And what would setTheFunction() look like? What type of argument would you have to pass?
You can use Callable.
public class A<V> {
public int a;
public int b;
private Callable<V> callable;
public A(int a, int b) {
this.a = a;
this.b = b;
}
public V theFunction() {
try {
return callable.call();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void setTheFunction(Callable<V> callable) {
this.callable = callable;
}
}
Then, to use it:
final A<Integer> test = new A<Integer>(3, 2);
test.setTheFunction(new Callable<Integer>() {
int x = test.a * test.b;
return x * x + 2;
});
System.out.println(test.theFunction());
Of course, the generic typing of A isn't necessary, but I've added it to make this answer to be less restricted.
If you always need to operate on the same arguments, you could solve this by defining an interface such as:
public interface MethodPerformer {
int performOperation(int a, int b);
}
Then pass in implementations of this to your setTheFunction method. Finally, invoke the operation when you call the other method:
class A {
int a;
int b;
MethodPerformer performer;
A(int a, int b) {
this.a=a; this.b=b;
}
int theFunction() {
performer.performOperation(a, b);
}
void setTheFunction(MethodPerformer performer) {
this.performer = performer;
}
}
Clearly additional code would be required to check the performer is not null. Perhaps take a performer in the constructor?
Instead of using a setter, the more natural way is to use an anonymous sub-class. This way the compiler will check it behaves correctly and has access to the right variables.
public class Main {
static abstract class A {
protected int a, b;
A(int a, int b) {
this.a = a;
this.b = b;
}
public abstract int theFunction();
}
public static void main(String... ignored) {
A test = new A(3, 2) {
#Override
public int theFunction() {
int x = a * b;
return x * x + 2;
}
};
System.out.println(test.theFunction()); // Should return (3*2)*(3*2)+2 = 38
A test2 = new A(1, 5) {
#Override
public int theFunction() {
for (int i = 1; i < b; i++) a = a * b * i;
return a;
}
};
System.out.println(test2.theFunction());
}
}
prints
38
15000
With this you can solve any kind of problem, that involves any kind of public variable of A (but can work with package private variables as well, if the AFunction implementation resides in the same package), that a function may use to perform it's operation. It's just not as compact as it can be in other languages than java.
interface AFunction
{
int call(A a);
}
class A
{
int a;
int b;
//giving it a default implementation
private AFunction f = new AFunction()
{
#Override
public int call(A a)
{
return a.a * a.b;
}
};
A(int a, int b)
{
this.a = a;
this.b = b;
}
int theFunction()
{
return f.call(this);
}
void setTheFunction(AFunction f)
{
this.f = f;
}
}
By the way as AlexTheo points out, all answers so far (except for Peter Lawrey's) are a form of the strategy design pattern.
The easiest way to do this is defining "A" as an interface instead of a class. You declare theFunction() without actually implementing it.
In client code, everytime you need "A", you instantiate a so-called anonymous inner class.
For example:
new A() { #Override public int theFunction() { ...your implementation... } };
How I can get arithmetical operators at run-time in Java? Suppose if I have values
ADD it should add the number
MUL then it should multiply the number
For Example
public calculate(int x, String str){
while(str.equals("some value")){
If( str.equals("ADD"))
// it should return me something like x+
if( str.equals("MUL"))
it return me something like x*
}
if( str.equals("FINAL"))
it should return me x+x*x
}
What you need is not runtime metaprogramming, but first class functions.
The following represent first class functions, with arity 1 and 2 respectively.
abstract class UnaryFunction<A, B> {
public abstract B apply(A a);
}
abstract class BinaryFunction<A, B, C> {
public abstract C apply(A a, B b);
}
For the sake of simplicity, let's use specialized versions of above classes.
abstract class UnaryOperation {
public abstract int apply(int a);
}
abstract class BinaryOperation {
public abstract int apply(int a, int b);
}
Now construct a dictionary of the required arithmetic operations.
Map<String, BinaryOperation> ops = new HashMap<String, BinaryOperation>();
ops.put("ADD", new BinaryOperation() {
public int apply(int a, int b) {
return a + b;
}
});
ops.put("MUL", new BinaryOperation() {
public int apply(int a, int b) {
return a * b;
}
});
// etc.
Add a method that partially applies BinaryOperation on one parameter.
abstract class BinaryOperation {
public abstract int apply(int a, int b);
public UnaryOperation partial(final int a) {
return new UnaryOperation() {
public int apply(int b) {
return BinaryOperation.this.apply(a, b);
}
};
}
}
Now we can write your calculate method.
public UnaryOperation calculate(int x, String opString) {
BinaryOperation op = ops.get(opString);
if(op == null)
throw new RuntimeException("Operation not found.");
else
return op.partial(x);
}
Use:
UnaryOperation f = calculate(3, "ADD");
f.apply(5); // returns 8
UnaryOperation g = calculate(9, "MUL");
f.apply(11); // returns 99
The abstractions used in the above solution, namely first class function interfaces and partial application, are both available in this library.
public class Calculator {
public static enum Operation {ADD, MUL, SUB, DIV};
private int x; // store value from previous operations
public void calculate(int x, Operation operation) {
switch(operation) {
case ADD:
this.x += x;
break;
case MUL:
this.x *= x;
break;
case SUB:
this.x -= x;
break;
case DIV:
this.x /= x;
break;
}
}
public int getResult() {
return this.x;
}
}
To use it elsewhere in your code:
public static void main(String[] args) {
Calculator c = new Calculator();
c.calculate(4, Calculator.Operation.ADD);
// Other operations
c.getResult(); // get final result
}
Assuming you are trying to just add and multiply x, just do the following:
public int calculate(int x, String str) {
// while(true) is gonna get you into some trouble
if( str.equals("ADD")) {
return x + x;
}
else if( str.equals("MUL")) {
return x * x;
}
else
return x; // not sure what you want to do in this case
}