Prasanna Raman wrote:Hello,
I don't understand the usage of "ob1.t.isAlive()" in the code below. I just don't understand that construct. Please help me understand how "ob1.t.method" works.
I know what the isAlive() method does, but just confused about the usage "ob1.t" to call it.
The ob1 portion is a local variable, which is a reference to a New class type. The New class object has an instance variable, named t, which is a reference to a Thread class type. So, to access this Thread object, you need to use "ob1.t".
You have a reference called ob1 which has an accessible field called t and that t has a method called isAlive().
Prasanna Raman wrote:Sorry, I am still not getting it. Could you please explain differently? I am trying to think if there may be other cases where we use this construct? Generally we call any method of a class using an object of the class.. is t an object of thread here? Then I understand t.isAlive() but how does ob1 come fit in here?
Well, simply, because it won't work. The "t" variable is not directly in scope here -- there is no "t" variable as part of your test class, or as a local variable of the main() method. So, "t.isAlive()" won't work here.
But you already know that because t points to Thread objects (or null).
Prasanna Raman wrote:Could you please give me an example for how a different construct could be used here?
You seem to be under the impression that this is some magical construct -- that is different from other reference variable types... However, given a reference variable to an object, you can access fields like so "var.field" and you can call methods like so "var.method()". But just what is a field? It is just a variable -- including a reference variable. What is returned from a method? It can possibly return a reference to an object.
How is this field, or reference return from a method different from any other variable? Well, it isn't much different. You can use the field as a variable to access the field of the object that the field variable points to ... like "var.field.anotherfield".
"But just what is a field? It is just a variable -- including a reference variable. What is returned from a method? It can possibly return a reference to an object.
How is this field, or reference return from a method different from any other variable? Well, it isn't much different."
This explanation from you has done the trick for me! I think I now understand this. Please confirm if my understanding is right,
"t" is just a field in the New class, just like "i" being a field if there was an "int i" declaration in the same class.
So, "t" is a field, but just that it happens to be an object of some other class thereby having the ability to access methods of that class to which it belongs.
So, "ob1.t" is just accessing the "t" field of New class, and with "t" being an object, it's possible to call a method on that object by "ob1.t.isAlive()".