Java. Instance variable value access via this operator - java

i need someone help with this little code snippet; why is the output: b 3 and not b 13 as expected?
public class Foo{
int a = 3;
public void addFive() { a+=5; System.out.println("f");}
}
class Bar extends Foo{
int a = 8;
public void addFive() { this.a+=5; System.out.println("b");}
public static void main(String[] args) {
Foo f = new Bar();
f.addFive();
System.out.println(f.a);// why b 3 and not b 13 ??
}
}

Foo and Bar have two different a fields; Java does not have any notion of field overriding.
Calling f.addFive() calls the derived version of the method (since Java does do method overriding), which modifies Bar.a.
However, accessing f.a returns Foo.a (since f is declared as Foo), which was never changed.

You have actually two variables called a: One in Foo and one in Bar.
In Bar.addFive you are modifying the variable a which is declared in Bar (not the one declared in Foo).
In addition, as variables do not show polymorphic behavior, you are accessing the variable a declared in Foo in your main method.

You are modifying a in Bar which is not the same as a in Foo, and your code is printing a of Foo
Here are some more code examples which might make you understand whats going on
Foo f = new Bar();
f.addFive();
System.out.println(f.a);//3
System.out.println(((Bar)f).a);//13
Bar b = new Bar();
b.addFive();
System.out.println(b.a);//13

Java does not have dynamic binding for variable instances but just on methods. When you access a field, the most specialized one (in case of name clash, like in your example) is not chosen.
The chosen one will be the one for which the variable has been declared, not the runtime one. To have dynamic bimding you shoul use a getter and not reference direcly to the variable.

The rules are simple.
Polymorphism does not apply to:
static methods
private methods.
variables.
overloaded methods.
Generics
All the above happens in Compile time and is called Compile time binding or static binding
Dynamic Binding or Runtime binding is done in Method Overriding.

I got ya, first of all there is overriding in JAVA. However, What you are doing is not methods overriding if you do this it will work as you want:
public class Foo{
int a = 3;
public void addFive() { a+=5; System.out.println("f");}
public int getA() {return a;}
}
class Bar extends Foo{
int a = 8;
public void addFive() { this.a+=5; System.out.println("b");}
public int getA() {return a;}
}
I hope you get the problem.

Foo f = new Bar();
f.addFive();
f.addFive() executes the overriden method of Bar class. In the next line
System.out.println(f.a);
This retrieves the variable a of Foo class, which is 3 (as it is not changed).
So you got 3 as answer.

Related

Java output explanation [duplicate]

Consider the int a variables in these classes:
class Foo {
public int a = 3;
public void addFive() { a += 5; System.out.print("f "); }
}
class Bar extends Foo {
public int a = 8;
public void addFive() { this.a += 5; System.out.print("b " ); }
}
public class test {
public static void main(String [] args){
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
}
}
I understand that the method addFive() have been overridden in the child class, and in class test when the base class reference referring to child class is used to call the overridden method, the child class version of addFive is called.
But what about the public instance variable a? What happens when both base class and derived class have the same variable?
The output of the above program is
b 3
How does this happen?
There are actually two distinct public instance variables called a.
A Foo object has a Foo.a variable.
A Bar object has both Foo.a and Bar.a variables.
When you run this:
Foo f = new Bar();
f.addFive();
System.out.println(f.a);
the addFive method is updating the Bar.a variable, and then reading the Foo.a variable. To read the Bar.a variable, you would need to do this:
System.out.println(((Bar) f).a);
The technical term for what is happening here is "hiding". Refer to the JLS section 8.3, and section 8.3.3.2 for an example.
Note that hiding also applies to static methods with the same signature.
However instance methods with the same signature are "overridden" not "hidden", and you cannot access the version of a method that is overridden from the outside. (Within the class that overrides a method, the overridden method can be called using super. However, that's the only situation where this is allowed. The reason that accessing overridden methods is generally forbidden is that it would break data abstraction.)
The recommended way to avoid the confusion of (accidental) hiding is to declare your instance variables as private and access them via getter and setter methods. There are lots of other good reasons for using getters and setters too.
It should also be noted that: 1) Exposing public variables (like a) is generally a bad idea, because it leads to weak abstraction, unwanted coupling, and other problems. 2) Intentionally declaring a 2nd public a variable in the child class is a truly awful idea.
From JLS
8.3.3.2 Example: Hiding of Instance Variables This example is similar to
that in the previous section, but uses
instance variables rather than static
variables. The code:
class Point {
int x = 2;
}
class Test extends Point {
double x = 4.7;
void printBoth() {
System.out.println(x + " " + super.x);
}
public static void main(String[] args) {
Test sample = new Test();
sample.printBoth();
System.out.println(sample.x + " " +
((Point)sample).x);
}
}
produces the output:
4.7 2
4.7 2
because the declaration of x in class
Test hides the definition of x in
class Point, so class Test does not
inherit the field x from its
superclass Point. It must be noted,
however, that while the field x of
class Point is not inherited by class
Test, it is nevertheless implemented
by instances of class Test. In other
words, every instance of class Test
contains two fields, one of type int
and one of type double. Both fields
bear the name x, but within the
declaration of class Test, the simple
name x always refers to the field
declared within class Test. Code in
instance methods of class Test may
refer to the instance variable x of
class Point as super.x.
Code that uses a field access
expression to access field x will
access the field named x in the class
indicated by the type of reference
expression. Thus, the expression
sample.x accesses a double value, the
instance variable declared in class
Test, because the type of the variable
sample is Test, but the expression
((Point)sample).x accesses an int
value, the instance variable declared
in class Point, because of the cast to
type Point.
In inheritance, a Base class object can refer to an instance of Derived class.
So this is how Foo f = new Bar(); works okay.
Now when f.addFive(); statement gets invoked it actually calls the 'addFive() method of the Derived class instance using the reference variable of the Base class. So ultimately the method of 'Bar' class gets invoked. But as you see the addFive() method of 'Bar' class just prints 'b ' and not the value of 'a'.
The next statement i.e. System.out.println(f.a) is the one that actually prints the value of a which ultimately gets appended to the previous output and so you see the final output as 'b 3'. Here the value of a used is that of 'Foo' class.
Hope this trick execution & coding is clear and you understood how you got the output as 'b 3'.
Here F is of type Foo and f variable is holding Bar object but java runtime gets the f.a from the class Foo.This is because in Java variable names are resolved using the reference type and not the object which it is referring.

Why is it necessary to declare a field as final when to be used in an inner class? [duplicate]

a can only be final here. Why? How can I reassign a in onClick() method without keeping it as private member?
private void f(Button b, final int a){
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
int b = a*5;
}
});
}
How can I return the 5 * a when it clicked? I mean,
private void f(Button b, final int a){
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
int b = a*5;
return b; // but return type is void
}
});
}
As noted in comments, some of this becomes irrelevant in Java 8, where final can be implicit. Only an effectively final variable can be used in an anonymous inner class or lambda expression though.
It's basically due to the way Java manages closures.
When you create an instance of an anonymous inner class, any variables which are used within that class have their values copied in via the autogenerated constructor. This avoids the compiler having to autogenerate various extra types to hold the logical state of the "local variables", as for example the C# compiler does... (When C# captures a variable in an anonymous function, it really captures the variable - the closure can update the variable in a way which is seen by the main body of the method, and vice versa.)
As the value has been copied into the instance of the anonymous inner class, it would look odd if the variable could be modified by the rest of the method - you could have code which appeared to be working with an out-of-date variable (because that's effectively what would be happening... you'd be working with a copy taken at a different time). Likewise if you could make changes within the anonymous inner class, developers might expect those changes to be visible within the body of the enclosing method.
Making the variable final removes all these possibilities - as the value can't be changed at all, you don't need to worry about whether such changes will be visible. The only ways to allow the method and the anonymous inner class see each other's changes is to use a mutable type of some description. This could be the enclosing class itself, an array, a mutable wrapper type... anything like that. Basically it's a bit like communicating between one method and another: changes made to the parameters of one method aren't seen by its caller, but changes made to the objects referred to by the parameters are seen.
If you're interested in a more detailed comparison between Java and C# closures, I have an article which goes into it further. I wanted to focus on the Java side in this answer :)
There is a trick that allows anonymous class to update data in the outer scope.
private void f(Button b, final int a) {
final int[] res = new int[1];
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
res[0] = a * 5;
}
});
// But at this point handler is most likely not executed yet!
// How should we now res[0] is ready?
}
However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated
This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:
// ...
final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);
// ...
An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):
Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.
I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.
(Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)
You can create a class level variable to get returned value. I mean
class A {
int k = 0;
private void f(Button b, int a){
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
k = a * 5;
}
});
}
now you can get value of K and use it where you want.
Answer of your why is :
A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).
Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)
To understand the rationale for this restriction, consider the following program:
public class Program {
interface Interface {
public void printInteger();
}
static Interface interfaceInstance = null;
static void initialize(int val) {
class Impl implements Interface {
#Override
public void printInteger() {
System.out.println(val);
}
}
interfaceInstance = new Impl();
}
public static void main(String[] args) {
initialize(12345);
interfaceInstance.printInteger();
}
}
The interfaceInstance remains in memory after the initialize method returns, but the parameter val does not. The JVM can’t access a local variable outside its scope, so Java makes the subsequent call to printInteger work by copying the value of val to an implicit field of the same name within interfaceInstance. The interfaceInstance is said to have captured the value of the local parameter. If the parameter weren’t final (or effectively final) its value could change, becoming out of sync with the captured value, potentially causing unintuitive behavior.
Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like
public class Test
{
public final int a = 3;
or as a local variable, like
public static void main(String[] args)
{
final int a = 3;
If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.
public class Test
{
public int a;
public void doSomething()
{
Runnable runnable =
new Runnable()
{
public void run()
{
System.out.println(a);
a = a+1;
}
};
}
}
You can't have a variable as final and give it a new value. final means just that: the value is unchangeable and final.
And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).
It just copies over the value of a into an implicit int called a in your anonymous class.
The reason why the access has been restricted only to the local final variables is that if all the local variables would be made accessible then they would first required to be copied to a separate section where inner classes can have access to them and maintaining multiple copies of mutable local variables may lead to inconsistent data. Whereas final variables are immutable and hence any number of copies to them will not have any impact on the consistency of data.
When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.
(http://en.wikipedia.org/wiki/Final_%28Java%29)
Methods within an anonomyous inner class may be invoked well after the thread that spawned it has terminated. In your example, the inner class will be invoked on the event dispatch thread and not in the same thread as that which created it. Hence, the scope of the variables will be different. So to protect such variable assignment scope issues you must declare them final.
private void f(Button b, final int a[]) {
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
a[0] = a[0] * 5;
}
});
}
As Jon has the implementation details answer an other possible answer would be that the JVM doesn't want to handle write in record that have ended his activation.
Consider the use case where your lambdas instead of being apply, is stored in some place and run later.
I remember that in Smalltalk you would get an illegal store raised when you do such modification.
Try this code,
Create Array List and put value inside that and return it :
private ArrayList f(Button b, final int a)
{
final ArrayList al = new ArrayList();
b.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
int b = a*5;
al.add(b);
}
});
return al;
}
Java anonymous class is very similar to Javascript closure, but Java implement that in different way. (check Andersen's answer)
So in order not to confuse the Java Developer with the strange behavior that might occur for those coming from Javascript background. I guess that's why they force us to use final, this is not the JVM limitation.
Let's look at the Javascript example below:
var add = (function () {
var counter = 0;
var func = function () {
console.log("counter now = " + counter);
counter += 1;
};
counter = 100; // line 1, this one need to be final in Java
return func;
})();
add(); // this will print out 100 in Javascript but 0 in Java
In Javascript, the counter value will be 100, because there is only one counter variable from the beginning to end.
But in Java, if there is no final, it will print out 0, because while the inner object is being created, the 0 value is copied to the inner class object's hidden properties. (there are two integer variable here, one in the local method, another one in inner class hidden properties)
So any changes after the inner object creation (like line 1), it will not affect the inner object. So it will make confusion between two different outcome and behaviour (between Java and Javascript).
I believe that's why, Java decide to force it to be final, so the data is 'consistent' from the beginning to end.
Java final variable inside an inner class[About]
inner class can use only
reference from outer class
final local variables from out of scope which are a reference type (e.g. Object...)
value(primitive) (e.g. int...) type can be wrapped by a final reference type. IntelliJ IDEA can help you covert it to one element array
When a non static nested (inner class) is generated by compiler - a new class - <OuterClass>$<InnerClass>.class is created and bounded parameters are passed into constructor[Local variable on stack] It is similar to closure[Swift about]
final variable is a variable which can not be reassign. final reference variable still can be changed by modifying a state
If it was be possible it would be weird because as a programmer you could make like this
//Not possible
private void foo() {
MyClass myClass = new MyClass(); //Case 1: myClass address is 1
int a = 5; //Case 2: a = 5
//just as an example
new Button().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
/*
myClass.something(); //<- what is the address - 1 or 2?
int b = a; //<- what is the value - 5 or 10 ?
//illusion that next changes are visible for Outer class
myClass = new MyClass();
a = 15;
*/
}
});
myClass = new MyClass(); //Case 1: myClass address is 2
int a = 10; //Case 2: a = 10
}
Maybe this trick gives u an idea
Boolean var= new anonymousClass(){
private String myVar; //String for example
#Overriden public Boolean method(int i){
//use myVar and i
}
public String setVar(String var){myVar=var; return this;} //Returns self instane
}.setVar("Hello").method(3);

Why local variable can not be changed in inner class?

I will show you two code bunchs.
public class A {
int globalVariable;
public void foo() {
globalVariable++;
class B {
void foo() {
System.out.println(globalVariable);
}
}
B b = new B();
b.foo();
}
public static void main(String[] args) {
A a = new A();
a.foo();
}
}
here i declared one global variable, changed its value, declared one inner class and created instance of this class.This code will work well and print
1
Now check out this code:
public class A {
public void foo() {
int localVariable;
localVariable++;
class B {
void foo() {
System.out.println(localVariable);
}
}
B b = new B();
b.foo();
}
public static void main(String[] args) {
A a = new A();
a.foo();
}
}
i did all steps on first code except here variable is not global but local.Here i get an exception that says localVariable must be final or effectively final.I googled and understood that this is why value gets captured and passed to class.When we changed it class doesn't know about this changes and it cause confusing.
i have 2 questions:
1.if it cause some confusing and we have to not change it after declaration
why we don't get this exception on global variable
2.it it is about local variable value changes so we have to get this exception only if we change this value after class instance declaration.Isn't it?
1) I think your first question is answered by Why a non-final "local" variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can?. (The question was earlier marked as a duplicate of that one.) Note that in general, the rule about not being allowed to modify variables doesn't apply to instance fields, or array elements, that are part of an object referenced by those variables. Therefore, this is legal:
public void foo() {
int[] localVariable = new int[1];
localVariable[0]++;
class B {
void foo() {
System.out.println(localVariable[0]);
}
}
B b = new B();
b.foo();
}
2) Your second code snippet can't succeed anyway, because you're incrementing localVariable before you've assigned a value to it, and that breaks the rules about "definite assignment". As for why Java doesn't let you use a variable that isn't modified after the inner class is declared: I don't know for sure. However, in Java 7 and earlier, the rule was that a local variable (or parameter) had to be declared final in order for it to be used in an inner class. In Java 8, this was relaxed--you didn't have to declare a variable or parameter final, as long as it was effectively final. However, I think the rule is that to be effectively final, the compiler determines whether the variable or parameter could have been declared final. And in this case, it can't, because this is illegal:
public void foo() {
final int localVariable = 3;
localVariable++;
}
In theory, the Java designers could have added rules to make the compiler determine whether a variable could be modified after a certain point. But that would have been more complicated, and it wouldn't have gained much, since you can still say
public void foo() {
int localVariable = 3;
localVariable++;
final int finalLocalVariable = localVariable;
class B {
void foo() {
System.out.println(finalLocalVariable);
}
}
}
Declaring a final variable to hold a copy of some other variable is a fairly common idiom when using inner classes, at least from what I've seen.

No parentheses in java

I am learning Java and I have learned that methods use parentheses for passing parameters. However, I have also noticed that sometimes I see code which to me looks like a method but it does not have parentheses.
MyObject.something()
MyObject.somethingElse
Where somethingElse does not have parentheses. I assume this is similar to how an arrayList has the size method for getting its size:
myList.size()
whereas an array has length to get its size, which does not have parentheses:
myArray.length
Is my assumption correct? If not, what is the difference?
This is probably an elementary question, but because of the amount of words I need to explain this problem, I have had trouble searching for it.
somethingElse is a property (data member), not a method. No code in the class is run when you access that member, unlike with a method where code in the class is run.
Here's an example:
public class Foo {
public int bar;
public Foo() {
this.bar = 42;
}
public int getBlarg() {
// code here runs when you call this method
return 67;
}
}
If you create a Foo object:
Foo f = new Foo();
...you can access the property bar without parens:
System.out.println(f.bar); // "42"
...and you can call the method getBlarg using parens:
System.out.println(f.getBlarg()); // "67"
When you call getBlarg, the code in the getBlarg method runs. This is fundamentally different from accessing the data member foo.
it is a class field which isn't a private field (usually it can be protected,package or public), so you can take it straight from your class. Usually fields are private, so you cannot take it like this outside your class definition.
myList.size() call a method defined in list class (public defined)
myArray.length call a property in array class not method
public class MyClass{
public int length;
public int size(){
....
}
}
MyClass mc =new MyClass();
mc.length;
mc.size();
This is triggering method called something of the instantiated object called someObject.
someObject.something();
This is accessing a property of the object called someObject (property which is public, most probably).
someObject.name

Java - when to use 'this' keyword [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
What is the best practise for using the this keyword in Java? For example, I have the following class:
class Foo {
Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
}
That's fine and all, but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
So why use the this keyword? (I realise in some situations, it's totally necessary to use it, I'm just asking for situations like this). Actually, I tend to use the keyword purely for readability sake but what's the common practise? Using it all over the shop makes my code look a bit messy, for example
boolean baz;
int someIndex = 5;
this.baz = this.bar.getSomeNumber() == this.someBarArray[this.someIndex].getSomeNumber();
Obviously a poor bit of code but it illustrates my example. Is it just down to personal preference in these cases?
but Java is clever enough to know what is happening if I change the statement in the constructor to
bar = bar;
FALSE! It compiles but it doesn't do what you think it does!
As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.
As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
You should use it when you have a parameter with the same name as a field otherwise you will run into issues. It will compile, but won't necessarily do what you want it to.
As for everywhere else, don't use it unless it's needed for readability's sake. If you use it everywhere, 20% of your code will consist of the word 'this'!
this keyword refers to the Object of class on which some method is invoked.
For example:
public class Xyz {
public Xyz(Abc ob)
{
ob.show();
}
}
public class Abc {
int a = 10;
public Abc()
{
new Xyz(this);
}
public void show()
{
System.out.println("Value of a " + a);
}
public static void main(String s[])
{
new Abc();
}
}
Here in Abc() we are calling Xyz() which needs Object of Abc Class.. So we can pass this instead of new Abc(), because if we pass new Abc() here it will call itself again and again.
Also we use this to differentiate variables of class and local variables of method. e.g
class Abc {
int a;
void setValue(int a)
{
this.a = a;
}
}
Here this.a is refers to variable a of class Abc. Hence having same effect as you use new Abc().a;.
So you can say this refers to object of current class.
Actually
baz = baz
will raise this warning
The assignment to variable baz has no
effect
So what you think is wrong, the local scope overrides the class attribute so you MUST use this keyword explictly to assign the variable to the class attribute.
Otherwise the variable accounted into assignment is just the one passed as a parameter and the class one is ignored. That's why this is useful, it's not a fact of readability, it's a fact of explicitly deciding which baz are you talking about.
I would say
use this wherever not using it would cause ambiguities (or compiler warning, that are more important), otherwise just leave it. Since its purpose is exactly to solve ambiguities when default assumptions (first check locals, then check class attributes) are not enough.
It is common to use this keyword in explicit constructor invocation. You can see an example from the documentation.
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 1, 1);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
public Foo(Bar bar) {
this.bar = bar;
}
is not the same as
public Foo(Bar bar) {
bar = bar;
}
In the second case the bar in scope is the parameter, so you assign it to itself. this.bar remains null.
Depending on convention, you can use it for readability. It stresses the fact that it's an object variable.
I also like to have setter arguments with the same name as the variable (looks better in method signature). You need this in this case.
It is a personal preference - choose a style and stick to it. I personally use this but others think it is redundant.
Personal preference, but I use it to solve ambiguities only, and I suppose in the very rare case to make it obvious that the assigned variable is a field. There are some projects where people use "this.field" on every single field reference. I find this practice visually distracting to the point of being obnoxious, but you should be prepared to see such code once in a while.
I secretly think there's a special place in hell for people who write 500 line classes that have 275 'this' keywords in them, but this style is found in some open source projects, so to each his own I guess.
I always try to use this keyword on local class objects.
I use it to visually remind me if an object is static object or class object.
It helps me and the compiler differentiate between method args and local class object.
public void setValue(int value){
this.value = value;
}
It helps me to visually remind me if there is such a local object in an inner/nested/anonymous class to differentiate it from encapsulating class objects. Because if there is not this prefixed, my convention will remind me that it is an object of the encapsulating class
public class Hello{
public int value = 0;
public boolean modal = false;
public class Hellee{
public int value = 1;
public getValue(){
if (modal)
return 0;
return this.value;
}
}
}
void set(int real)
{
this.real = real;
}
here this is a keyword used when there is instance variable is same as the local variable.
another use of this is constructor overloading. it can call the constructor in a overloaded constructor.
Use it for Cloning objects (by passing reference of itself through a copy constructor).
Useful for object that inherits Cloneable.
public Foo implements Cloneable {
private String bar;
public Foo(Foo who) {
bar = who.bar;
}
public Object getClone() {
return new Foo(this); //Return new copy of self.
}
}

Categories

Resources