This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I'm working on translating some code from VisualBasic to Java and I've encountered a snag when using the ByRef keyword in VB. That doesn't exist in Java!
How should I simulate a ByRef call in Java?
Edit: Just to clarify for those who don't know VB, ByRef identifies a variable in the parenthesis after calling a function and makes it so that when that variable is changes inside of the function, it will also change higher up where it is called as opposed to ByVal where only the value of the variable is remembered. Changing a ByVal variable in the method will not affect the variable where it is called.
You can't. Everything in Java is passed by value, including object references. However you could create a "holder" object, and modify its value inside a method.
public class Holder<T> {
T value;
public Holder(T value) {
this.value = value;
}
// getter/setter
}
public void method(Holder<Foo> foo) {
foo.setValue(something);
}
Java does not have an equivialent.
You either need to return the object from your method, and assign it back, e.g.
myInteger = doSomething(myInteger);
Or you need to make a wrapper object, these are often name a Holder.
If you have a variable named myInteger that you want some method to change, you
pass it to that method as a member of the "Holder" class.
e.g. (This can naturally be made into a generic)
class IntegerHolder {
public Integer myInteger;
}
IntegerHolder myHolder;
myHolder.myInteger = myInteger;
doSomething(myHolder);
//use the possibly altered myHolder.myInteger now.
Inside doSomething, you can now change myHolder.myInteger , and the method calling
doSomething() can see that change, e.g.
void doSomething(IntegerHolder holder)
{
holder.myInteger = holder.myInteger * 100;
}
Related
This question already has answers here:
Is there something like instanceOf(Class<?> c) in Java?
(8 answers)
Closed 7 years ago.
What's the correct syntax to make this work?
public boolean isTypeOf(Class type) {
return this instanceof type;
}
I intend to call it with:
foo.isTypeOf(MyClass.class);
The method will be overriden, otherwise I would just use instanceof inplace.
Use Class.isInstance(obj):
public boolean isTypeOf(Class type) {
return type.isInstance(this);
}
This method determines if the given parameter is an instance of the class. This method will also work if the object is a sub-class of the class.
Quoting from the Javadoc:
This method is the dynamic equivalent of the Java language instanceof operator.
I'm sorry if this is already asked but here is my question. I would like to create a function where the parameter that the user inputs can be any variable type, similar to System.out.println().
That being said how would I create that method?
public static void example(String, int, double, etc.) {
//Code here
}
You need to change all the method parameters types to Object.
public void myMethod(Object o){
// ...
}
Please note that in order to access o as a certain type of other class you will need to first test if it is in fact that class with if(o instanceof OtherClass) and then cast it with OtherClass o2=(OtherClass) o. Casting is expensive (hogs a lot of CPU (for a simple operation)) though so avoid if possible. If you just need a string representation of o then just call o.toString().
This question already has answers here:
What does "this" point to?
(5 answers)
Closed 4 years ago.
public class CommandForm extends Form implements CommandListener {
Display d;
public CommandForm(String msg) {
super(msg);
this.addCommand(exit);
}
private void showMessage(String title, String text) {
Alert a = new Alert(title, text, null, AlertType.INFO);
d.setCurrent(a, this);
}
public void prepare_view(Display d){
this.setCommandListener(this);
this.d = d;
}
public void show_view(){
d.setCurrent(this);
}
}
I do not know exactly what the 'this' keyword means in this example. My lecturer says it is the current object, when I inquire further, he said it is the CommandForm. Is that correct? When you pass in 'this' into a parenthesis, e.g setCommandListener(this) are you actually passing the CommandForm? The only way I know how to use 'this' is like this way, this.d = d. So this is kinda new to me.
He's right. If you call setCommandListener(this) you are passing a reference to the current object into the method. When you do this.d = d you are setting the variable d which is part of the class (i.e this) to the incoming value (in parenthesis).
Your lecturer is indeed correct. It's the current object, and this is simply a means to refer to the object currently in scope.
You use the keyword to pass the reference to other objects e.g. object.doSomethingWith(this), and/or resolve ambiguity between members and variables (e.g. this.x = x - there are two different xs here).
Check out the Java Language Specification section on 'this'.
Yes, the this keyword is a reference to that particular instance of the CommandForm class.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
passing by reference in Java doubts
(5 answers)
Closed 8 years ago.
If I have a class like the one below:
public class Foo()
{
private RandomObject randomObject = new RandomObject();
public RandomObject GetRandromObject()
{
return randomObject;
}
}
And in another class I do this:
public class Goo()
{
private Foo fooObject = new Foo();
public Goo()
{
RandomObject ro = fooObject.GetRandomObject();
ro.ChangeNumberVariable(23);
}
}
Will the fooObject have the randomObject NumberVariable changed to 23?
If not would I just have to have a method in Foo called SetRandomObject and just pass in ro? Would this be a good substitute for passing by reference in Java?
What if I just did this:
public class Goo()
{
private Foo fooObject = new Foo();
public Goo()
{
fooObject.GetRandomObject().ChangeNumberVarialbe(23);
}
}
Is it still not changing the NumberVariable?
In both cases fooObject.randomObject would have NumberVariable changed to 23. They are pretty much equivalent just the former uses an extra reference.
This does not make Java pass-by-reference. Java is pass by value. Any time you pass something to a method as a parameter it is copied, even if what you pass is a reference to an object.
Though you can use that copied reference to access and mutate the object on the end of it, as you are doing here, any re-assignment of that reference cannot escape the method.
In your first example doing:
ro = new RandomObject();
would not change anything about fooObject.randomObject.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
For those who ever wrote in C, C++ or ObjectiveC, understand Blocks is very simple. Why it's so difficult to get the concept in Java (8)?
I will answer my question!
Block
Just a list of statements surrounded by curly braces. That's all. A block is executed by executing its individual statements in sequence. It's nothing like the thing called a "block" in, for example, the Ruby programming language.
Closure
Java does not have closures, but it has something that looks like one:
int limit = ...;
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for (int i=0 ; i<limit ; i++) { ... }
}
});
That may look like the run() method refers to the variable limit in the outer scope, but it won't compile unless the variable limit is effectively immutable. What's really happening here is that the anonymous inner class has a member variable named limit, and a hidden constructor that takes an argument named limit, and the value is supplied to the constructor by copying the value of limit from the surrounding scope.
Lambda
More smoke and mirrors. The value of a lambda expression in Java is not a function: It's an instance of an anonymous inner class that implements a functional interface. The same code that I wrote above could be written more concisely as a Java lambda expression:
int limit = ...;
Thread t = new Thread(() -> {
for (int i=0 ; i<limit ; i++) { ... }
});
Java8 introduces the idea of an #Functional interface type which must declare exactly one method. In this case, they've retconned the java.lang.Runnable class to be #Functional
When the compiler reads the code above, it knows to make the anonymous class implement the Runnable interface because that's the only type that is accepted by the Thread constructor, and it knows that the body of the lambda should become the run() method, because that's the only method declared by Runnable.
All you need to understand is “type”.
A variable has a type. Eg:
int i, double d…
An object has a type (a class). Eg:
String s, Number n, Object o, MyClass m…
A function has a type. Eg:
void function () <= this type is: a function with no return and no param.
void function (type param) <= this type is: a function with no return with a param of type ‘type’
type function (type param) <= this type is: a function with a return of type ‘type’ and a param of type ‘type’
What is a block/closure/lambda?
It is basically a local function of a given type passed to an other function as parameter.
So we heard: a function that takes a function of a given type as parameter.
And the function which receive the function and launches it!
The main usage is: CallBack and Comparaison functions. But the dream up is open.
We can draw that as:
type function(type function_param) {
excute the function_param
}
How to say this in Java.
1/ declare the type of the block/closure/lambda
2/ create the function (in a class or not) which get that kind of type as param
3/ create the local function of the type of the block/closure/lambda
4/ pass it as param to the function which use it.
Eg:
// 1 declaring the type of block/closure/lambda
interface CallBack {
public int function(String string);
}
class MyClass {
private String name;
MyClass(String name) { this.name = name; }
void display () { System.out.println(this.name); }
// 2 creating the function that which that kind of type as param
int myFunction(CallBack funcCallBack) {
return funcCallBack.function(name);
}
}
public class Main {
public static void main(String[] args) {
// 3 Create the local function of the type of the block/closure/lambda
CallBack message = (String string) -> {
System.out.println("Message: "+string);
return 1;
};
MyClass mc = new MyClass("MyClass");
mc.display();
// 4 pass it as param to the function which use it.
int res = mc.myFunction(message);
System.out.println(res);
}
}
output
MyClass
Message: MyClass
1