Java Instantiation
- When an object is instantiated in Java, what is really going into memory?
- Are copies of parent constructors included?
- Why do hidden data members behave differently than overridden methods when casting?
I understand the abstract explanations that are typically given to get you use this stuff correctly, but how does the JVM really do it.
Asked by: Brad293 | Posted: 21-01-2022
Answer 1
When an object is instantiated, only the non-static data is actually "Created", along with a reference to the type of object that created it.
None of the methods are ever copied.
The "Reference" to the class that created it is actually a pointer dispatch table. One pointer exists for each method that is available to the class. The pointers always point to the "correct" (usually the lowest/most specific in the object tree) implementation of the method.
That way if you have a top-level call to another method, but the other method has been overridden, the overridden method will be called because that's where the pointer in the table points. Because of this mechanism, it shouldn't take more time to call an overridden method than a top-level one.
The pointer table + member variables are the "Instance" of a class.
The variable issue has to do with a completely different mechanism, "Name spaces". Variables aren't "Subclassed" at all (They don't go into the dispatch table), but public or protected variables can be hidden by local variables. This is all done by the compiler at compile time and has nothing to do with your runtime object instances. The compiler determines which object you really want and stuffs a reference to that into your code.
The scoping rules are generally to favor the "Nearest" variable. Anything further away with the same name will just be ignored (shadowed) in favor of the nearer definition.
To get a little more specific about memory allocation if you are interested: all "OBJECTS" are allocated on the "Heap" (Actually something amazingly more efficient and beautiful than a true heap, but same concept.) Variables are always pointers--Java will never copy an object, you always copy a pointer to that object. Variable pointer allocations for method parameters and local variables are done on the stack, but even though the variable (pointer) is created on the stack, the objects they point to are still never allocated on the stack.
I'm tempted to write an example, but this is already too long. If you want me to type out a couple classes with an extends relationship and how their methods and data effect the code generated I can... just ask.
Answered by: Haris390 | Posted: 22-02-2022Answer 2
I think you'll find this to be a comprehensive example:
http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html
Answered by: Abigail526 | Posted: 22-02-2022Answer 3
Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and itssuperclasses. Implementation-specific data includes pointers to class and method data.
The instance variables of the objects are initialized to their default values.
The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase.This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java.
Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then thebody of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
Similar questions
instantiation - KeyListener in Java is abstract; cannot be instantiated?
I am trying to create a Key Listener in java however when I try
KeyListener listener = new KeyListener();
Netbeans is telling me that KeyListener is abstract;cannot be instantiated. I know that I am missing some other piece of this key listener, but since this is my first time using a key listener i am unsure of what else i need. Why is it telling me this?
Thanks,
Tomek
With hessian in Java, how do you control instantiation?
I have a cache of objects (not the HTTP session attributes) and I want to be able to get an object from this cache when a Hessian request comes in and have Hessian execute the call on this object instead of the servlet.
I can control the class that the request is executed on by setting the service-class and api-class init parameters on the HessianServlet. However, it is performing the instantiation of objects itse...
java - How can I force instantiation of all referenced beans during Spring start-up?
My applicationContext.xml:
<bean id="studentService" class="com.coe.StudentService">
<property name="studentProfile" ref="studentProfile" />
</bean>
<bean id="studentProfile" class="com.coe.student.StudentProfile">
</bean>
My web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</list...
class - Self Instantiation in Java
How do I self-instantiate a Java class? I should not use any file other than its class file. Also assume that after the line where I initialized the NAME variable, they don't know the name of the class during compile-time.
Example:
public class Foo implements Bar {
public static final String NAME = "Foo";
private void instantiate() {
Bar baz = (Bar)Class.forName(NAME).newInstance()...
java - Why do some classes restrict direct instantiation?
I have encountered various classes that don't allow creation of their instance directly. Rather we have to create their instance from some other class's static method or it own static method. For example:
B b = A.getB();
or
B b = B.getInstance();
What reason is behind that?
Why don't they allow creating instance directly, as in:
B b...
Doubt related to interface instantiation in Java
The following program when run will product stackoverflow as output.
I want to know what is happening in the line where a TestA is being instantiated.
interface TestA { String toString(); }
class Test
{
public static void main(String[] args)
{
// whats going on in this line ???
System.out.println(new TestA() {public String toString() { return "stackoverflow"; } });
}
}
...
java - JFrame not working after first instantiation?
As part of a larger application, I am writing a settings class, which collects and stores user-defined settings. This class is a singleton, and is instantiated during application startup.
In order to accept user input, two different GUI frames are insantiated from within ConfigSettings.java, from a public static method, selectSettings(). Both are subclasses of JFrame. Here is the code for the instantiation of the ...
java - Copy constructor Class instantiation
Here is my class that implements copy constructor
public class TestCopyConst
{
public int i=0;
public TestCopyConst(TestCopyConst tcc)
{
this.i=tcc.i;
}
}
i tried to create a instance for the above class in my main method
TestCopyConst testCopyConst = new TestCopyConst(?);
I am not sure what i should pass as parameter. If i have to p...
java - Use of private constructor to prevent instantiation of class?
Right now I'm thinking about adding a private constructor to a class that only holds some String constants.
public class MyStrings {
// I want to add this:
private MyString() {}
public static final String ONE = "something";
public static final String TWO = "another";
...
}
Is there any performance or memory overhead if I add a priva...
java - Deep bean copy with strategy for null property instantiation
I am looking for the simplest way to do a deep copy of a flat Map<String, String> of nested properties to a bean. Some of the nested properties are interfaces for which I would like to provide a strategy for instantiation. For example:
Map<String, String> customer = new Map<String, String>();
customers.put("id", "123");
customers.put("address.line1", "221B Baker St.");
public class Cust...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)