简体   繁体   中英

Object, reference and class. Need help understanding some code

I kind of understand that:

  • A class is kind of a blueprint that objects can be created from.
  • A object is an actual instance or object that gets created.
  • A reference is like an address that points to said object.

What exactly happens when the below code is called twice?

Car batmobile = new Car();

Will two objects get created? If so, what happens to the first object? In detail, what happens in terms of class, object and reference?

Part 2:

Is this an infinite loop? Will objects keep getting created since the constructor makes an object and then calls on the constructor again? How does the class, object, reference relation work here?

public class Alphabet {
  Alphabet abc;

  public Alphabet() {
    abc = new Alphabet();
  }
}

Car batmobile = new Car(); Will two objects get created?

If it's called twice then yes. Because the line creates a new instance of an object. So doing that twice would result in two new instances. Note, however, that if you try to execute that same exact line twice in a row then you would get a compiler error because you'd be trying to re-declare the same variable in the same scope.

But otherwise, no, there's only one object being created on that line. Car is mentioned twice because it declares the type for the variable ( batmobile ) and for the constructor ( Car() ). Some languages (C#, JavaScript, untyped languages, etc. but not Java) have shorthand for the first use, since it's easily inferred from the second. For example:

var batmobile = new Car();

Is this an infinite loop?

Nope, there's no loop here:

Public class Alphabet{
    Alphabet abc;

    Public Alphabet(){
        abc = new Alphabet();
    }
}

There is , however, a stack waiting to be overflown. In order to create an Alphabet one must first create an Alphabet . Run the code and see the error. An infinite loop would just execute infinitely (assuming each iteration of the loop didn't compound the use of some finite resource), for example:

while (true) {
    Car batmobile = new Car();
}

This will execute without end. The code you posted, however, will end. With an error. Because each call to the constructor internally calls the constructor. The call stack is a finite resource, so it will very quickly be exhausted.

I use a cookie metaphor to explain Objects and Classes.

Think of the memory of a computer as a big lump of cookie dough. (Yummy, isn't it?)

Your class is a cookie cutter. It will create cookies of a particular size and shape as long as you have dough (memory). An object is a cookie cut with the cookie cutter.

1) batmobile is a reference to a Car object. It can only point to a Car or a subclass of car. It has no object instance (dough) attached to it when it is created. When you call new Car() you stamp out an object instance and assign it to a reference called batmobile. There is only one reference.

2) Don't do this. You might end up with a stack overflow, I'm not sure, but it's not going to get you the results that you want. You might want to look up Singleton pattern. It might help you.

Now I need help understanding what exactly happens when this code is called twice.

Ex: Car batmobile = new Car();

Will two objects get created?

A Car object will be created each time that line is executed, so if you execute it twice, yes, two objects are created.

If so what happens to the first object.

If nothing else has a reference to it, it becomes eligible for garbage collection by the JVM. When and whether that happens depends on many factors within the JVM's garbage collector.

Can someone explain in detail what happens in terms of class,object and reference.

Car batmobile

...declares a variable of type Car . Because it's an object type, the variable will end up holding an object reference (or null , which means it's not holding a reference to any object). The actual object exists independently of any variables that may have a reference to it (and there may be many references to one object). An object reference is like a memory address saying where in memory the object is. (It is not a memory address, but it's like one.)

new Car();

...creates a new Car object and calls the Car constructor to initialize it. So:

Car batmobile = new Car();

...declares a variable, creates an object, calls the Car constructor, and assigns a reference to that object to batmobile .

Is this an infinite loop?

It would be, but eventually you'll run out of stack space, so it's a stack overflow error . That line calls the Alphabet constructor, which calls the Alphabet constructor, which calls the Alphabet constructor... You get the idea.

Question 1

Car batmobile = new Car();

This creates one object. The object is of type Car and its identifier is 'batmobile'. In terms of its reference, batmobile will be popped onto the stack and it will contain a reference to an object of type Car on the heap.

This question may help with stack and heap memory explanations.

Question 2

Ironically, seeing as this is posted on SO, this example would result in a stack overflow error. Each call to the constructor creates a new object with a reference to it placed on the stack before calling the constructor again. The stack is an area of limited memory so eventually this is going to overflow and your program will terminate with a stack overflow error

In C++, when you write:

SomeClass x;

It automatically creates an instance of SomeClass . Not so in Java.

In Java, the same line above simply creates a variable named x whose type is SomeClass . The variable x doesn't refer to anything (any instance) until you initialize to something.

In Java, the line below creates one object and initializes the variable x to point to it.

SomeClass x = new SomeClass();

Your code block:

Public class Alphabet{
    Alphabet abc;

    Public Alphabet(){
        abc = new Alphabet();
    }
}

Doesn't actually do anything, since the constructor is never called. If you did call it like:

public static void main(String[] args){
    new Alphabet();
}

The following would happen:

  1. Create new instance of Alphabet
  2. Call constructor for Alphabet (from main method)
  3. Create new instance of Alphabet (to be assigned to member variable abc )
  4. Call constructor for Alphabet (from constructor of Alphabet)
  5. Continue recursion (steps 3 - 4) until StackOverflowError occurs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM