Can't call anonymous class method [duplicate] - java

This question already has answers here:
Using an arbitrarily defined method of an anonymous interface
(4 answers)
Closed 9 years ago.
I can imagine some very creative code in Java:
Object thing = new Object() {
public void speak() {
System.out.println("Hi!");
}
};
thing.speak();
Or even, to get the full closure effect, define a Function interface ... you get the idea?
Why doesn't this code work?

i believe you can do it like this :-
new Object() {
public void speak() {
System.out.println("Hi!");
}
}.speak();
may help you .

Not sure about the usefulness in this example, but some type of overriding method(s) on the original declaration is useful and because of it is overriding, you can call the methods. Otherwise in your case, just use the reflection as:
thing.getClass().getMethod("speak").invoke(thing);
and for the overriding method:
Object thing = new Object() {
public void toString() {
System.out.println("Hi! Me inside your mind!");
return "not today!";
}
};
thing.toString();

Related

why void method can not be called in system.out.println [duplicate]

This question already has answers here:
The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
(7 answers)
Closed 5 years ago.
Can somebody please answer why this code is giving error?
package hello;
public class Hello {
public void eat() {
System.out.println("eating");
}
private String run() {
return "dwedsdfsdfsdf fsdf rgdsfG";
}
public static void main(String[] args) {
//System.out.println("Hello bhopi");
//Hello hello = new Hello();
Hello mahir = new Hello();
//String y = mahir.eat();
System.out.println(mahir.run());
System.out.println(mahir.eat());
}
}
1) No method may accept as parameter an invocation to a void method.
It is like if you would pass a void argument to a method.
2) Here println() refers to the PrintStream.println() method as the out field is declared as PrintStream.
To compile fine when you invoke it, you have to specify an argument that matches to one of the overloaded versions of this method.
Because void method does not return anything, so there is nothing to print. The method System.out.print() expects an Object as a parameter to print.

How to manipulate a Variable from another class using a method call from that other class? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
public class Main{
.
.
.
Class class = new Class();
class.method(class.variableFromAnotherClass);
sysout(class.variableFromAnotherClass)
}
public class Class{
Int variableFromAnotherClass=0;
method(int var){
var=1;
}
}
Output:
0
Im dealing with a situation similar to the one above except with more variables in my version of "Class". My issue is that the method within "Class" does nothing to the variable being passed through. Why does this happen? Is it because the variable being passed through already belongs to the class? Any suggestions on What should I do to solve this problem?
The problem you are facing has to do with Java passing variables by reference, instead of by value. when variableFromAnotherClass is passed into class.method(int var), the int var variable is created from a copy of variableFromAnotherClass. so when var=1 is called, it updates the copy of variableFromAnotherClass, and not variableFromAnotherClass itself.
If you want to be able to change variableFromAnotherClass from Main, you can write class.variableFromAnotherClass=1; instead of calling method.
Another, more professional way of updating variables is using getters and setters:
public class Class {
int variableFromAnotherClass;
public void getVar() {
return variableFromAnotherClass;
}
public int setVar(int var) {
this.variableFromAnotherClass = var;
}
}
please make both the method and the variable static
public class Class{
static Int variableFromAnotherClass=0;
static method(int var){
var=1;
}
}
Try java getters and setter and make instance variables of another class private which will add encapsulation.

How to program behavior of a void method with Mockito? [duplicate]

This question already has answers here:
How to mock void methods with Mockito
(11 answers)
Closed 8 years ago.
I have a Controller class with something like this
public void create(int a, int b){
//do something
}
Now i want to mock the Controller class and call a certain method for exmaple doCustomCreate() when the create Method of my mocked Controller class is called.
My test would ´look something like this
Controller ctrlMock = mock(Controller.class);
//PseudoCode: when(isCalled(ctrlMock.create(a,b)).doCall(doCustomCreate());
I only read about mocking methods with input and return values, so i wondered if this is possible?
Edit: Updated the Question
Just use this API for void methods :
doAnswer(doCustomCreate()).when(ctrlMock).create(a,b);
Or with BDDMockito :
willAnswer(doCustomCreate()).given(ctrlMock).create(a,b);
Where doCustomCreate() returns an Answer (that returns null). Note I used Void just to indicate this answer don't return anything.
public Answer<Void> doCustomCreate() {
return new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
// your stuff
return null;
}
}
}
Note giving behavior to a mock is somehow a rocky path for maintainability of tests, as it means the tested component is not tested in pure controlled environment / isolation.
So you want to override the mock's behavior for a certain method. The solution for this is using a so-called spy (AKA partial mock) instead of a mock: http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#16

Java weird operator ()-> meaning and String operations [duplicate]

This question already has answers here:
What does the arrow operator, '->', do in Java?
(6 answers)
Closed last year.
Today I met part of weird code which I do not understand.
What can mean something like this ()->
for example
method( ()-> System.out.println("Hello") );
another question is, what is an output of String:
[AB][CD]*EF+(X/Y)
of course there were not any instance of A, B etc.But I there were answers like
ABCDEFX,
ACEFXX,
ACEFXA,
I do not remember them
Can anybody help me?
Suppose you have an interface that declares one method:
public static interface MyFunctionalInterface {
void m1();
}
And you have a method that receives an object of that type as a parameter:
public void method(MyFunctionalInterface i) { ... }
You can implement that interface and use it immediately using anonymous inner classes like this:
method( new MyFunctionalInterface() {
public void m1() {
System.out.println("Hello");
}
});
In Java 8 you can replace that with a lambda expression such as the one you showed:
method( () -> System.out.println("Hello"); );
The empty parameters represent the m1() method, with no parameters.
Suppose the functional interface you were using had a method with one parameter (if your method had the form method2(ActionListener s) { ... } for example), then you would use:
method2( e -> System.out.println("Hello"); );
which would be the same as doing this:
method2( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
There are many tutorials about Lambda expressions in Java 8. This one is a good quick-start.

Java Overloaded Constructors [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Understanding which constructor is chosen and why
Why compiler acts like this,
public class Calculator{
private Calculator(Object o) {
// code goes here
}
private Calculator(double[] calc) {
// code goes here
}
public static void main(String[] args) {
new Calculator(null);
}
}
This program executes second constructor. Why first constructor not execute?
Both constructors are accessible and applicable.
The constructor Calculator (Object) accepts any parameter passed to Calculator (double[]), so Calculator (Object) is less specific.

Categories

Resources