Passing in 'This' keyword [duplicate] - java

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.

Related

I don't understand this common java principle [duplicate]

This question already has answers here:
How to instantiate an object in java?
(7 answers)
Closed 5 years ago.
Currently I'm following java course and I am struggling with a part of the code which I see used a lot in methods. So here goes:
Answer answer = new Answer("something");
I have a class named Answer and I think the first Answer is in reference to that. the lower cased answer is the variable. It's after the = sign I'm struggling to comprehend. any help please?
This declares a variable answer of type Answer and initializes it with a new object instance of class Answer by calling the Answer(String) constructor.
Consider Apollo's comment and google it.
This is not only a java principle but a generall programming principle.
You're creating a new Answer Object.
Let's look at this example:
public class Answer{ // The class
private String answer; // internal variable only visible for the class
public Answer(String answer){ // This is a constructor
this.answer = answer; // Here we assign the String we gave this object to an internal variable
}
public void setAnswer(String answer){ // Setter
this.answer = answer;
}
public String getAnswer(){ // Getter
return answer;
}
}
So now you have a class/Object named Answer.
When you now want to use it you need to create a new Object.
This is done over the constructor of a class. ( Constructor = basically a definition of what you need to create the Object )
First you declare what Object you want your variable to be, then you give the variable a name you can use it under.
That looks like this:
Answer variableName
But this will not create a new object.
To create it we need to give the keyword new in combination of a Constructor of the object we want to create.
As we defined a constructor that needs a String to create this object we need to call it like this:
new Answer("the string");
If we combine those two we finally have our usable new variable of a new create Answer
Answer yourVariable = new Answer("the string");
Any declaration in Java follows the following rules:
[variable type] [variable name] = [value];
So in your case:
variable type = object of type Answer
variable name = answer
value = new Answer("something")
What you're doing with new Answer("something") is that you're creating a new object of type Answer using the constructor that accepts a single String
Notice that the value is optional. You can just declare any value and assign a value after that
This is a pretty basic concept in Java.
Once we define a Java class, we can create objects of such class. To do so, we need to call a special method in the class, called constructor, with the reserved keyword new. Additionally, we want to store a reference to the newly created object in a variable, so that we can use it later.
To do so, we first declare a variable of the type of the class:
MyClass myVariable;
And then create an object and assign it to the variable:
myVariable = new MyClass();
In your case, the constructor receives one parameter of type String for initializing the object.

Execute certain methods on object creation from constructor [duplicate]

This question already has answers here:
Can I call methods in constructor in Java?
(7 answers)
Closed 7 years ago.
Alright, I think this is a faily simple question, but I just can't wrap my head around this.
Lets say I have this pseudo classes with their respective functionalities. Can I call the methods from within the constructor itself, so it launches on object creation?
Class One
public class Apples{
public String a;
public String b;
Apples(String a, String b){
this.a = a;
this.b = b;
specificMethod();
}
public void randomMethod(){
System.out.println(this.a)
}
public void specificMethod(){
System.out.println(this.b)
}
}
Class Two
public class Oranges{
Apples green = new Apples(a,b)
}
Yes, if you put a method in an object constructor which is called it will run the methods inside the constructor.
Yes.
Many people will even just call an _init function instead of doing everything inside the constructor. That way you can reinitialize an object without creating a new one.

What is the equivalent to "ByRef" in Java? [duplicate]

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;
}

Java supports pass-by-value. But can't make out the reason of the below code [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
Code:
class AB{
int i=5;
}
class BC{
public void test(AB a){
a.i=10;
}
}
public class ATest{
public static void main(String aa[]){
AB a = new AB();
//Base class variable value
System.out.println(a.i);
BC b = new BC();
//Modifying the object "a"
b.test(a);
//Printing the base class object
System.out.println(a.i);
}
}
// Output : 5
// 10
If it is pass-by-value, the output should have been 5 and 5
Java uses pass-by-value but if the parameter is an object Java passes by value the reference to the object, so the called method can change the content of the object, not the object as a whole.
This does not mean that objects are passed by reference (the comment by Joachim Isaksson is wrong).
ADDED to answer to the comment by Arijeet Saha:
When I say "the called method can change the content of the object, not the object as a whole", I mean that if you change the object as a whole the caller doesn't see the change.
Consider the following example:
public void test(Person p) {
p.setName("Pino");
p = new Person();
p.setName("John");
}
The first line of test() changes the content of the object received by the method, the second line changes the object as a whole (it assigns a new object to the formal parameter), the third line changes the content of the new object. In this case the caller sees a Person object with name "Pino", not "John", because the change made by the second line of test() is not visible to the caller; it is not visible because objects are not passed by reference.
Let me first clear what does pass-by-value mean?
It means what ever you are passing to a method, it will recieve its copy not the actual adress.
So in your case you too are passing the value the variable a, and its value (which is referance to an object or adress to an object) is copied to the method(AB a).
Java's parameter passing is quite tricky - When an object is passed to a function, you can manipulate the object's fields but you cannot manipulate object itself. The object reference is passed by value. So, you can say:
class someClass{
int i = 5;
}
class Foo
{
static void func(someClass c)
{
c.i = 3;
}
}
class MainClass{
public static void main(){
someClass c = new someClass();
System.out.println(c.i);
Foo.func(c);
System.out.println(c.i);
}
}
Expect your output to be:
5
3
Changes to the fields of c persist.
but if manipulate the object itself, this manipulation will only persist in Foo.func() and not outside that function:
class someClass{
int i = 5;
}
class Foo
{
static void func(someClass c)
{
c.i = new someClass();
c.i = 3;
System.out.println(c.i);
}
}
class MainClass{
public static void main(){
someClass c = new someClass();
System.out.println(c.i);
Foo.func(c);
System.out.println(c.i);
}
}
Expect your output to be:
5
3
5
What has happened? c.i has the value 5 in MainClass.main() in Foo.func(), c itself is modified to point to another instance of someClass, containing the value 3. However, this change is not reflected to the actual object that has been passed. The c in Foo.func() and MainClass.main() are different objects now. That's why changes to the c of Foo.func() do not affect the c in MainClass.main().
Java always passes parameters as by value.
It's important to understand what is the value (what a variable holds).
For primitives it's the value itself.
For objects it's a reference.
When you pass an object as a parameter - the reference to the object is copied but it still points to the original object.

What does "this" mean? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java this.method() vs method()
I've been reading some things and doing some tutorials about android java but I still dont understand what "this" means, like in the following code.
View continueButton = this.findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = this.findViewById(R.id.new_button);
newButton.setOnClickListener(this);
Also why is it in this example that a button is not defined with Button but with View, what is the difference?
ps. Great site!! trying to learn java and got ALLOT of answers by searching here!
The this keyword is a reference to the current object. It is used to pass this instance of the object, and more.
For example, these two allocations are equal:
class Test{
int a;
public Test(){
a = 5;
this.a = 5;
}
}
Sometimes you have a hidden field you want to access:
class Test{
int a;
public Test(int a){
this.a = a;
}
}
Here you assigned the field a with the value in the parameter a.
The this keyword works the same way with methods. Again, these two are the same:
this.findViewById(R.id.myid);
findViewById(R.id.myid);
Finally, say you have a class MyObject that has a method which takes a MyObject parameter:
class MyObject{
public static void myMethod(MyObject object){
//Do something
}
public MyObject(){
myMethod(this);
}
}
In this last example you passed a reference of the current object to a static method.
Also why is it in this example that a button is not defined with Button but with View, what is the difference?
In Android SDK, a Button is a subclass of View. You can request the Button as a View and cast the View to a Button:
Button newButton = (Button) this.findViewById(R.id.new_button);
this is referring to the instance of the object that is being acted upon.
In the case that you have above, this.findViewById(R.id.continue_button) this is referring to a method in a parent class (Specifically either Activity.findViewById() or View.findViewByid(), assuming you are writing your own subclass of Activity or View!).
this refers to the current instance of a class
this in Java is a reference to the current object instance. So if you are writing a method for class MyClass, this is the current instance of MyClass.
Note that in your case, writing this.findViewById(...) isn't really necessary, and may be considered bad style.
"this" in object oriented languages such as java, c# is a reference to the object on which you are invoking the method or whose data you are accessing.
See if this link is helpful for you in understanding the "this" more -
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
"this" is the current object instance.
class Blaa
{
int bar=0;
public Blaa()
{}
public void mogrify(int bar,Blaa that)
{
bar=1; //changes the local variable bar
this.bar=1; //changes the member variable bar.
that.bar=1; //changes "that"'s member variable bar.
}
}

Categories

Resources