this!!

Hi! Everybody. This is my first time here. I am sure you'll see me here often asking lots of questions! Here's my doubt: I understand that using 'this' for static instance variables makes no sense becoz they are class variables. Also I read that it is illegal to use 'this' with class variables. But I have a code here that compiles and runs too!! What's wrong?? Is it just plain redundant or is it illegal? <CODE>public class StaticTest { static int total=15; StaticTest (int x) { System.out.println("In test"); this.total=x; if (this.total> 5) { System.out.println(this.total); }} public static void main (String args []) { StaticTest obj1=new StaticTest(7); StaticTest obj2=new StaticTest(8); System.out.println(obj1.total);//Output,of course,is 8!! } } </CODE>

It has no compiling error. I think it is because of the static var is accessed inside the constructor. One question: When could you conside the object construction is done? At the end of constructor? Is "this" valid at the beginning of the constructor?

No, it is not illegal. But if you try to use this under a static context, your compiler will cry, as in the following: class A{ static int x; public static void main(String[] argv){ System.out.println("compiler crying " + this.x); } }

hi 'this' refers to the current object. So this.variable refers to a variable belonging to that object(i.e. the object is the owner of that variable). However the static variables also belong to that object, though it is not the sole owner of the static object. Hence we can refer to static object as this.bariable. hope you get what I mean regards Tanveer

Author of JPhotoBrush Pro (www.jphotobrushpro.com)

Tanveer Rameez
Ranch Hand

Joined: Dec 11, 2000
Posts: 158

posted Dec 19, 2000 00:23:00

0

hi 'this' refers to the current object. So this.variable refers to a variable belonging to that object(i.e. the object is the owner of that variable). However the static variables also belong to that object, though it is not the sole owner of the static object.The static variables are jointly owned by all the instances of that class. Hence we can refer to static object as this.bariable. hope you get what I mean regards Tanveer

Ash Rai
Ranch Hand

Joined: Dec 15, 2000
Posts: 34

posted Dec 19, 2000 01:07:00

0

Well this is what I gather.. Consider the following code that has been included in the above example. public void method (){ System.out.println("Total is:"+ this.total);} 1. Since this is a non static method I can refer to total as either this.total or total. Both will compile and run. 2. If method is declared as public static void method() then I CANNOT refer to total as this.total. Thank you all..

You are correct. But for point 2, you can't use this in any static method, not just main(). Reason is that static can be called without creating an object, so if there is no object, what does this refer to? Bill