• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is it possible to use new ***() as the argument directly?  RSS feed

 
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Crystal Zeng wrote:. . . Page 361

Thank you. I don't have my copy to hand now, but can look later.
 
Bartender
Posts: 18870
77
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Devid Smith wrote:

I think you should put the idea that "an object can't be used directly" out of your head. The bottom line is that you need an object reference in order to use an object and there are other ways you can obtain an object reference besides assigning one to a reference variable.


Its such a good idea.I agree with you on 100%
What are the methods in question?Thanks in advance



System.out.println(new StringBuilder("Hello ").append("World!").toString());

The StringBuilder object is constructed, its object reference anchors the "append()" method invocation, which returns another object reference (in this case, the appended "Hello " Stringbuilder. That object reference anchors toString(), which decants the appended StringBuilder buffer as a printable String.

Disclaimer - without checking the javadocs, I don't remember if StringBuilder's appen() method supports method chaining. I think it does, but as an abstract example, I hope this demonstrates. Everything was done within the context of an expression argument to println() and no variable assignment was ever made.

Also, note that the StringBuilder object goes out of scope as soon as the println call returns and is thus immediately eligible for garbage collection.
 
Campbell Ritchie
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Tim Holloway wrote:. . . I don't remember if StringBuilder's appen() method supports method chaining. . . .

Yes it does.
The toString() call is redundant.
 
Tim Holloway
Bartender
Posts: 18870
77
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Tim Holloway wrote:. . . I don't remember if StringBuilder's appen() method supports method chaining. . . .

Yes it does.
The toString() call is redundant.



True, but I was hammering the point. The println() method has an implied toString() operation when asked to print an object which isn't itself a String.
 
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Crystal Zeng wrote:My confusion comes from the mind that I always think of new **() as an object and an object isn't allowed to be used directly.The book called <Head First Java>never says new operator will return a reference.From the descriptions below, I tend to think of the right side of = operator as an object.


This goes back to Bear's original point about programmers using shortcut notations to avoid saying "object reference" vs. "object" all the time. In many cases, in fact I'd say usually, "reference" and "object" are interchangeable. You just have to learn to discern when the distinction between the two matters in the context of the discussion and when it doesn't.

I think you should put the idea that "an object can't be used directly" out of your head. The bottom line is that you need an object reference in order to use an object and there are other ways you can obtain an object reference besides assigning one to a reference variable.


Only if you see the img named 444PNG(put your mouse around the img until the mouse is changed to "hand" icon and click it, it can be displayed), you may understand why I tend to think of the right side of = operator as an object rather than a reference according to the description based on the img.
1. Can you provide strong evidence to say new operator returns a refernce?
2.It is so strange for a book read by beginners not to descripe clearly every time it refers to "reference "or"object" instead of abbreviating , I mean as accurate as math concept.

-444.PNG
[Thumbnail for -444.PNG]
 
Saloon Keeper
Posts: 3448
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "object" occupies some space in RAM (memory), the reference is a sort of "address" where that object is located.

When you have an array of, say, Animals, what you really have is an array of references to Animals.
 
Tim Holloway
Bartender
Posts: 18870
77
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider a language like C++. In C++ there are 3 ways to pass a parameter to a function:

1. Pass a value. This puts a copy of the object (often a numeric literal primitive) on the parameter list. Changes to the copy in the called routine do not reflect back to the calling code.
2. Pass a pointer. This passed a value that is the memory address of the object. To access a property of the object pointed to by "x", the notation is "x->a_property".
3. Pass a reference. This passes a pointer undercover with direct-access semantics. Instead of "x->a_property", the syntax is "x.a_property".

In Java there are fewer options. For primitives, a simple value is passed. For objects, a reference is passed. Also, unlike C++, the actual object reference value is almost certainly not a pointer. It's far more likely to be a "handle", which is an anchor address to a relocatable item within the object space. Those are internal implementation details, however, and not available to java bytecode logic.

"new" is not a value, it is an operator. Specifically, it can be considered as an implicit invocation of the object class newInstance() method. Thus, the result of the "new" operator/the return value will be a reference to the newly-created object. To see that in action, consider the following code:



In the first line, a new String object is created. A reference to that object is then assigned to "s". In the third line, "s" is then assigned a value of null. Obviously, then, s is not itself the jabberwocky String. Strings are immutable and on top of that, null isn't an object, it's a "non-value".

The variable s1 is set to the value of s. Here, again, we're working with a reference. If we were working with an actual object, then either s1 would require s to be cloned (and the value of 's==s1' would be false), or the line that sets s to null would have the side-effect of implicitly setting s1 to null. Neither of those things happen, so the jabberwocky string becomes eligible for garbage collection only after both s and s1 have been set to null, destroying all references to the jabberwocky string.

Incidentally, I used to work with someone who routinely used new String() constructor. There is an actual use for it, but not in most code.



Also note that garbage collection is not predictable or instantaneous. When security professionals write Java code, they don't store passwords and other sensitive information in String objects. Instead they use character or byte arrays. That's because Strings are immutable and cannot be erased, whereas an array of primitives can be manually cleared immediately after use by application logic (just set all the elements to blank/zero/X/garbage or whatever). When a String goes out of reference the time while it's still in memory awaiting garbage collection is time that an ill-intentioned hacker can break into the JVM looking for password-like objects and harvesting them. By using a destructable object like a character array, that time can be made near-zero, thus reducing the opportunity for mischief.
 
Sheriff
Posts: 22949
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Stephan van Hulst wrote:If we're being pedantic, the new keyword is an operator that takes a class name and an argument list, and returns a reference to a new object.



Yes, we are being pedantic. That seems to be the major point of this thread -- sloppy terminology can lead to misunderstandings, especially in the case of people who are new to Java. So we do need to be pedantic sometimes, and this is one of those times.
 
Tim Holloway
Bartender
Posts: 18870
77
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Speaking of being pedantic, that illustration is horrible. Contrary to what it says, the variable is not a reference, the variable holds a reference.

This is as erroneous as thinking that the name of a thing is the same as the thing itself.

I highly recommend reading Lewis Carroll's [i]Alice Through the Looking-glass" in the chapter where she encounters the White Knight and he elaborates on a song, the name of the song, and what the song is called. I've always felt it made a good example of how pointers work, but I think it applies equally well here.
 
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Crystal Zeng wrote:
Only if you see the img named 444PNG(put your mouse around the img until the mouse is changed to "hand" icon and click it, it can be displayed), you may understand why I tend to think of the right side of = operator as an object rather than a reference according to the description based on the img.


You are misinterpreting what that text is trying to explain in the diagram. It's partly because of the shortcut terminology used but it's partly because you don't have a clear understanding yet. Maybe you should just leave this for now and move on to other examples. When you have more clarity from other examples, revisit this particular topic and see if your understanding of it becomes clearer. Many of us have attempted to clarify things and I'm afraid the chorus of voices trying to do so has only made it more confusing for you. Nevertheless, I'll try one more time.

What the book says:
But with polymorphism, the reference and the object can be different.

The looong version, without using shortcut terms:
The right hand side of the assignment statement, new Dog(), will create a new Dog object. Since you can only access objects through references, the new operator will actually return a reference to the new Dog object that it created. That reference is then assigned to the myDog variable, which has a declared type of Animal. If you're wondering how the type of the myDog variable can be different from the type of the reference returned by the new operator that is assigned to it, it's because of polymorphism. Since a Dog is a subclass of Animal, a reference to a Dog object can be assigned to a reference variable for an Animal object. This is because whatever you can do with an Animal, you should also be able to do with a Dog.



Crystal Zeng wrote:1. Can you provide strong evidence to say new operator returns a refernce?


I already pointed out before that The Official Java Tutorial says this:

The Offical Java Tutorial wrote:The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory.


(see https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html) If that still isn't strong enough evidence for you, then maybe someone can dig up a reference to the ultimate authoritative reference on Java, the Java Language Specifications.

Crystal Zeng wrote:2.It is so strange for a book read by beginners not to descripe clearly every time it refers to "reference "or"object" instead of abbreviating , I mean as accurate as math concept.


I don't know, maybe the authors were betting that more people would find it easier to read their version than something like the very long-winded explanation that I gave above. Sometimes information can get buried under too many facts.<shrug>
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here are more examples fashioned after the examples in the polymorphism track of the Official Java Tutorial: (https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)

This is the concept that the diagram you're confused about is trying to show. The comments above exemplify the kind of verbal shortcuts we use. Those who already understand when to distinguish "reference type" from "object type" from "object reference type" can understand when one term can be used interchangeably with any of the others. But again, it would be very wordy, noisy, and would come off as somewhat pedantic actually if it were commented with more precision:

So you see, authors also have to strike a good balance between precision, brevity, and clarity.
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Junilu Lacar, Thank you for your detailed reply.I got it.
You know, I take every words of a book seriously. Since the book never says new operator can return a reference. (for example,in the picture named  333.PNG,it just says new **() means creating an object in Step 2. It just says linking the object and a reference , not saying linking a reference returned by new operator and a reference variable in Step 3. In the picture named 888.PNG, it just says "Assign the two Book objects to the reference variables  " rather than "Assign the two reference returned by new operator to the reference variables" .),That is why I always thought of new ***() as creating an object rather than not only creating an object , but also a reference returned by new operator.
Given the evidence from you,it seems  I have to repair my mind.
-333.PNG
[Thumbnail for -333.PNG]
-888.PNG
[Thumbnail for -888.PNG]
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
resend the picture named 888.PNG.
you have to put your mouse around the "888.PNG" and when the mouse icon is changed to "hand"icon, click it and you can see the picture content.
It is so strange for the forum that some pictures can't be displayed directly.
-888.PNG
[Thumbnail for -888.PNG]
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm glad that gives you a little bit more clarity. You do have a point about that diagram though, I can see how it was confusing you. Let me try to help you adjust that picture so it fits better with the way we've just described things.

1. Animal myDog = new Dog();

Declares a reference variable that can be assigned (someone suggested "that can hold") a reference to any Animal object. The picture here should be just of an empty cup labeled "myDog", with no remote inside it. The empty cup is the reference variable myDog. Let's just say that the shape of the cup is the declared type Animal (imagine a generic shape that can represent any kind of animal)

2. Animal myDog = new Dog();

Creates a Dog object and a reference to that object. The picture for this should be of the circle (the new Dog object) and a remote linked to the circle by an arrow (the reference that the new operator linked to the new Dog object). This is because the new operator also returns a reference to the new Dog object it created. At this point, the reference is there but nothing has been done with it yet, so it's still just "floating" around with the object that it's linked to. This is why you can also do this:

new Dog().bark();  // take the "floating" reference that new has created and call that Dog's bark() method with it

3. Animal myDog = new Dog();.

The reference to the new Dog object is assigned to the reference variable, myDog.  So the picture for this should still have the remote linked to the new Dog object, except now the remote is inside the cup labeled "myDog". That is, the cup (i.e. the reference variable named myDog) should now "hold" the remote (the reference returned by new Dog()) that is linked to the actual new Dog object that's somewhere in memory.

The remote for a Dog will fit in a cup that's shaped for any Animal because of polymorphism and inheritance: a Dog is an Animal, so naturally a remote for a Dog will fit in a cup for any Animal.  If you tried to put a remote (i.e. a reference linked to an object) in that same cup (i.e. the reference variable myDog that's shaped to hold any Animal remote) and the remote wasn't linked to some kind of Animal (either an Animal or a subclass of Animal), then it would not be allowed because that non-Animal remote DOES NOT have the right shape that will allow it to fit in a cup that was shaped to hold only Animal type remotes.

That's a lot of words but hopefully it creates the right pictures to set your mind straight.
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For future reference, and using the same analogy, here are a few more points:

The type of remote created by new Dog() is always a Dog remote and never an Animal remote. Likewise, new Animal() will always create an Animal remote and never a Dog remote or Giraffe remote.  And new Giraffe() always a Giraffe remote, never a Dog remote or Animal remote.

This is what you'll normally see being referred to as the "actual type" or the "runtime type". In the book, it seems like this was referred to simply as "the object type," which is why it confused you. The old-timers are used to this "shortcut" so we didn't really get confused.

The "shape" of the cup we talked about is normally referred to as the "declared type" or the "reference type".  So, in normal parlance, when you have Animal myDog = new Dog();, we say "Animal is the declared type of the myDog (reference) variable but the actual type (or runtime type) of the object it references is Dog."



 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now that I think about it, it's probably better if you replace "cup" in our analogy with "case".  Imagine a case, or frame if you will, for a remote.  A Dog remote will have "buttons" to make it bark, sit, run, eat, wag its tail. A Dog remote can fit in a case made for any kind of Animal remote. However, the Animal case only has holes that allow the buttons for run and eat to be pressed. Any other button the Dog type remote might have besides eat and run will be covered up by the Animal case.  If you have a Cat remote that has a meow button in addition to its run and eat buttons, then the meow button would be covered up if the Cat remote was put inside an Animal case.

That's why the reference variable can be declared a different type from the actual object but can still hold a reference to that object as long as the object "fits" the definition of the reference variable type.  So a Dog fits the definition of an Animal because Dog extends Animal.  The reverse is not true though. You can't have this: Dog myDog = new Animal(); because the remote for Animal is too big for a case that's meant for any kind of Dog only.

I'll stop now and let you process all that for a while.
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Junilu Lacar
Thank you very much.
I appreciate your precision about illustration.
You are so nice.
 
Creator of Enthuware JWS+ V6
Saloon Keeper
Posts: 3064
248
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Congratulations Crystal Zeng,

Your question has made it to our Journal  

Have a Cow!
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not necessarily true that
new Dog( );
does nothing / is useless. It depends on what the constructor does.


Dog( ) {
    kennel.add(this);
}

where kennel presumably is a static structure, stores a reference for later use.
 
Campbell Ritchie
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Highlight the code, then push the code button, and it will look like this:-. . .Don't write code like that; never pass a reference to this to anything before the constructor completes. It is a breach of the Single Responsibility principle, that a class always takes care of itself. In this case the dog is taking care of part of the kennel. The kennel ought to take care of itself. Also, if you are in a multi‑threaded environment it is possible for the dog to be added to the kennel before it is completed and the kennel might use the dog instance in an inconsistent state. That can lead to errors which are difficult to understand.
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I absolutely agree with Campbell, you should avoid such machinations in a constructor not only for the technical reasons that Campbell cited but also for the semantics of the design. Doing that kind of thing tightens the coupling between the Dog class and whatever that kennel object is and the interaction with it from the Dog constructor represents a hidden side-effect of instantiating a Dog. The tighter coupling also makes Dog more difficult to unit test because now you have to make sure that the kennel reference is always valid. Consider what the code would look like with that proposed design:

Having the kennel reference variable as a static field of the Dog class makes no sense semantically: Why would a Dog have a reference to a Kennel? That's kind of like having a Student class keep a reference to an instance of a ClassRoom. The coupling problem would be even worse if kennel were declared and encapsulated elsewhere. Either way, the design is not good.
 
Gerard Charles
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The topic is Why is it possible to use new ***() as the argument directly?.  The untrue statement that was made was that following no one has a reference to it. I've demonstrated that, without inspection of the constructor, you can't know that that's true. I didn't say it was a good idea. I will say that assuming code that you did not write follows a particular coding style / practice definitely isn't a good idea, and if you don't realize that, you haven't been coding long enough.
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No need to get defensive or argumentative. Don't take comments personally and likewise, don't lash out and make things personal with comments like "you haven't been coding long enough."  Folks around here literally have a combined experience of hundreds of years of programming in many industries and we all learn from each other.

Your point that you can't just assume that a constructor does nothing useful is true in the most basic sense. However, that's not the context in which we've been discussing "usefulness" -- we've not been concerned so much about what happens under the covers, inside the constructor. Rather, the discussion is around what can be done with the object reference created by new Dog(). When it's not assigned to a reference variable, the usefulness and scope of the object reference is limited to the immediate line of code. After that, you "lose" the reference and there's no getting it back. If you don't hold the reference somewhere so you can get back to it later, then there's no way to make use of it, i.e. it's now useless once program execution goes past the immediate line of code. That's the context of "usefulness" in this discussion.

As far as our comment regarding your example, many years of experience tells us that side-effects are generally problematic, especially ones that are not obvious or semantically reasonable, as was pointed out. Constructors should stick to initializing the state of the instance being created.

 
Campbell Ritchie
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Gerard Charles wrote:. . . I will say that assuming code that you did not write follows a particular coding style / practice definitely isn't a good idea, and if you don't realize that, you haven't been coding long enough.

I take that as meaning you are saying other people are coding badly. [Maybe that isn't what you are trying to say.] I can understand that; you always have to take precautions against people using your code badly or providing bad code for you to use. But I think it is a bit overpessimistic to expect that people will supply you with badly‑written code. That is also, partially, what the /** documentation comments */ are there for: to explain any side‑effects.
 
Gerard Charles
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course people will supply you with "badly" written code. (Imperfect is probably a better descriptor). I'm well paid to write imperfect code, as the editor / compiler / run time tests remind me on a daily basis. This is hardly a new realization; as Frederick Brooks explained in Mythical Man Month  "The programmer builds from pure thought-stuff: concepts and very flexible representations thereof.  Because the medium is tractable, we expect few difficulties in implementation; hence our pervasive optimism. Because our ideas are faulty, we have bugs; hence our optimism is unjustified."

Any active code project will have a bug repository, specifically because humans produce imperfect code.
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for Step One, when declaring a reference variable before assigning it a reference to an object, does a reference pointing to nothing exist in this variable?
The distinction for this picture is either there is a remote without linking an object in the cup,or just an empty cup.Which one is more accurate?
I think of a reference as a remote.
1.PNG
[Thumbnail for 1.PNG]
2.PNG
[Thumbnail for 2.PNG]
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
(The pictures above come from this link)
 
Gerard Charles
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Meaning depends on context, so what Point origin; means depends on where it's declared:

Integer y , being in class scope is implicitly initialized to null by the Java Virtual Machine (JVM). Local variable Integer x isn't initialized to anything and is undefined (like 3/0). Attempting to use it creates a compile time error.
 
Campbell Ritchie
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Crystal Zeng wrote:As for Step One, when declaring a reference variable before assigning it a reference to an object, does a reference pointing to nothing exist in this variable? . . .

A field defaults to pointing to null, as do elements of arrays before they are filled.
 
Ranch Hand
Posts: 120
1
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow! what is an "event object" ??? I never heard this term before in my life, it's in none of my java books, never was mentioned in any java classes I attended.
Also here's a mind bender, where is the reference returned to if you don't assign it? To NULL? To the code block where that method was called from? Or is the interpreter smart enough to know never to even send it?
 
Campbell Ritchie
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

S Fox wrote:wow! what is an "event object" ??? . . .

Not 100% certain, but I am pretty sure it is an instance of one of the event classes for GUIs. I suggest you start with the Java™ Tutorials, and see whether that helps.
Have a look at the documentation for a kind of event. If you follow its inheritance hierarchy upwards, you will see event object one level below Object. Click upon that, and upon the page there is a list of subclass derived upon that class and it tells you things happen upon other objects.

Briefly: if you do just about anything to a GUI, anything from moving the mouse across it to clicking a button, an event occurs. In many situations multiple events occur. Those events travel through the different components of the GUI; if any of those components is listening for it, that component can catch the event object and that fires another method. Otherwise, the event object disappears behind the back of the GUI and goes into cyber‑limbo never to be seen again. Some events are listened to without your noticing. If, for example, you bring a GUI from the back to the front, its repaint method will be called so it becomes visible. That happens without your having to write any code for it.
 
S Fox
Ranch Hand
Posts: 120
1
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's really weird, I never thought of events as being objects but just something that the listener detected. So you could do something like Event e = new Event(null); and make a fake event, then somehow feed it into a listener for testing purposes? Or capture all the input and store it as a list of event objects? I guess this is how you can make a program to record and play back macros. I will definitely look into this more.
 
Campbell Ritchie
Marshal
Posts: 56820
173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

S Fox wrote:. . . I never thought of events as being objects . . .

Well, that is the idea of an object language

So you could do something like Event e = new Event(null); . . .

Don't know, but probably yes. Go through the methods of JComponent and see whether there is anything for firing events.
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Crystal Zeng wrote:As for Step One, when declaring a reference variable before assigning it a reference to an object, does a reference pointing to nothing exist in this variable?
The distinction for this picture is either there is a remote without linking an object in the cup,or just an empty cup.Which one is more accurate?
I think of a reference as a remote.


Be careful about interpreting these illustrations -- both those images are correct but they are not using your cup-remote-TV metaphor. If you think about it in terms of that metaphor and the way I explained it to you before, then

is essentially an empty cup labelled "originOne". This is nuanced by what others have pointed out: Depending on where this declaration occurs, the originOne variable may be implicitly initialized to null or not initialized at all, i.e. there might be "dummy" remote that doesn't work with any TV (implicitly initialized to null if it's a field declaration) that is put into the cup or nothing at all (not initialized if it's a local variable declaration).

Of course, when you assign an object reference to the variable, you definitely are putting a remote (the reference to the new object) that works with a specific TV (the new object) into the cup (the reference variable) labelled "originOne".
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

S Fox wrote:... here's a mind bender, where is the reference returned to if you don't assign it? To NULL? To the code block where that method was called from? Or is the interpreter smart enough to know never to even send it?


No, the unused reference is not "returned to NULL"—there is no such thing as "returning to null" even. Think of it like buying a lottery ticket and then forgetting where you put it. The ticket is now useless to you because you don't have physical possession of it and this is analogous to not assigning an object reference to a variable.

However, just as the lottery ticket still exists somewhere, the object and the reference will remain in memory until the Garbage Collector comes around and determines that the memory they occupy can be reclaimed for other uses. Essentially, the Garbage Collector sees if anything can still get to the reference so that the object it points to can be used. If nothing can get to the reference, then nothing can use the object, therefore, the memory occupied by both the reference and the object can be reclaimed. Think of the GC as the cleaning person who doesn't see a lottery ticket but a discarded scrap of paper on the ground that needs to be swept up and thrown in the incinerator.

Search for how does garbage collection in Java work or see these: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html and https://www.dynatrace.com/resources/ebooks/javabook/how-garbage-collection-works/
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Of course, when you assign an object reference to the variable, you definitely are putting a remote (the reference to the new object) that works with a specific TV (the new object) into the cup (the reference variable) labelled "originOne".


When Assigning an object reference to the variable , does it means copying the reference into the variable? If so, what happens to the original reference? Will it be collected by GC?   I think assigning A to B means copy A 's value into B , does it right?
 
Junilu Lacar
Sheriff
Posts: 11532
181
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see why it would matter much, honestly. Why do you think it does?

On line 1 above, there is only one reference to the new object that was created, nothing was copied. On line 2, now there are two references to the same object after the reference is copied to the reference variable b.
 
Crystal Zeng
Greenhorn
Posts: 24
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:
Thank you so much. I got it now.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!