I know the functions are loaded only once in the memory. My doubt is... if we create an object of a class how it refer the function? What is the thing behind the object creation and function calling? Is there any pointer in the object to the function?
I believe you're looking for the term "virtual method table".
This is the mechanism that languages (compilers) use to determine what method to actually invoke when a call to a virtual function is made (and in Java all functions are virtual).
When you create an object, only it's data fields are being created (allocated). Class methods forever resides in memory during whole program run.
Does object have pointer to the method or no is language-dependent. For example, in C++ object are containing pointers to virtual methods, while normal and static methods are called just by their constant addresses.
Related
I have a Doubt and i can't find it on google or on Youtube, so I am Asking here.
As we know,
Instance methods can call other Instance Methods directly without objects in the same class. However we need objects to call Instance method in a Static method.
I want to ask why is it so? How does Instance method calls other instance method directly without object but need an object to get called inside a Static method?
Because instance methods already have the object. You can access it with the this keyword. When you call an instance method in an instance method, it calls it on this unless you specifically call it on another instance. In a static method you don't have an object, so there is no this object to call it on. So unless you specify an instance there's no default to call it on.
Why doesn't the language force you to call it on this rather than assume? Convenience, it allows you to type a bit less. Its a common feature in other object oriented languages as well. There are languages that won't do it and require you to specify the object at all times.
I would like to know that if I have the following class.
class Example {
public static void method1() {}
public void method2() {}
public void method3() {}
}
Only 1 method is static and it should be the first thing to be loaded in the memory during runtime. But what about the instance methods? Are they loaded in the memory when an instance of this class is created? Or are they already loaded when the class is loaded initially.
What I am trying to understand is if it is a better approach to have all the functionality in the same class by having separate methods for each functionality or is it better to create a separate class for each functionality with only there respective methods in its class.
So will it help memory wise in the later case because I will only create the instance of the class that I need to use and only that much of methods will be loaded in the memory. Otherwise, in the former case, where I have 100 methods in the same class, but I only need to use just 2 methods out of them, it will be waste of memory because all 100 methods are loaded.
Any suggestions?
Actually memory allocation for class variables and class member functions/methods are done differently. When a class is being instantiated its class variables are being created in the memory which is call as data segment and method codes are created in code segment. IF we create ten objects of a particular class java virtual machine will create ten different code segments but only one code segment will be created for all the object. Java virtual machine will create a code segment only when there is at least one reference to that that class object in the code else it will not.
Code segment captured minimal memory only. It just stores assembly instructions created from code. Hence you no need to worry about it. For object also a programmer no need to worry about managing the memory in Java as there is a garbage collector in java.
Now answer to your question in my comment section:-
But will the methods themselves be stored somewhere in heap etc. ? So a class having 100 methods or 2 methods will behave the same memory wise?
As I said your method's codes will be converted into assembly instruction by your java virtual machine and will be stored in the memory in an instruction pointer for each method. Not necessarily now many method, it will depends on lines of code, recursion, loops, and condition etc. Yes if 100 methods of same size of codes with all the above then it will takes more memory than two methods.
is there any term call Virtual Constructor in Java?then where we need to use this?
Virtual Constructors are not a part of the Java language, but the term might be applied to some design patterns
For example, calling object.clone() on an object that supports it will produce a new object (much like new ClassName(object) if you have a copy constructor) and thus resembles a constructor, but is polymorphic. In "Effective Java" Joshua Bloch advocates the use of Static Factory methods as another way of achieving polymorphic object creation in certain circumstances.
For the use of the term in the C++ context look at: http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8
I'm not sure what you mean by "virtual constructor." Constructors are called recursively up the class hierarchy. Every constructor must call its super-class constructor as the first thing. (The call can be omitted if it is to the no-arg constructor, in which case the compiler will automatically insert it.)
As an aside, Java doesn't have virtual methods. Or, more precisely, every instance method is virtual (in the C++ sense).
What do you mean by virtual constructors? If it is like virtual function in C++ there is no virtual constructor in java.
Not that I'm aware off. "Default Constructor " yes. Delphi has virtual constructors, most other languages does not. See the Factory pattern for something related.
Depending on the definition of virtual constructor. If by virtual constructor, you mean static method that calls a private constructor as part of some factory patterns, then yes there are virtual constructors. I have found them very useful at times, when methods must be called on self after construction. All you have to do is simply set the constructor to private, and within the class, include a static method that creates the class object instance and returns it. This is useful when methods need to be called on the object before the user is able to use it. Since it is a very bad idea to refer to self in the constructor due to the fact that the object is not fully constructed, one can use a virtual constructor to call the methods after instantiation and before the user may have access to it.
I'm preparing for an exam in Java and one of the questions which was on a previous exam was:"What is the main difference in object creation between Java and C++?"
I think I know the basics of object creation like for example how constructors are called and what initialization blocks do in Java and what happens when constructor of one class calls a method of another class which isn't constructed yet and so on, but I can't find anything obvious. The answer is supposed to be one or two sentences, so I don't think that description of whole object creation process in Java is what they had in mind.
Any ideas?
What is the main difference in object creation between Java and C++?
Unlike Java, in C++ objects can also be created on the stack.
For example in C++ you can write
Class obj; //object created on the stack
In Java you can write
Class obj; //obj is just a reference(not an object)
obj = new Class();// obj refers to the object
In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
Let's imagine a Base class, with a virtual method foo().
Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
In Java, calling foo() from the Base class constructor will call Derived.foo()
In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html
Besides heap/stack issues I'd say: C++ constructors have initialization lists while Java uses assignment. See http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6 for details.
I would answer: C++ allows creating an object everywhere: on the heap, stack, member. Java forces you allocate objects on the heap, always.
In Java, the Java Virtual Machine (JVM) that executes Java code has to might1 log all objects being created (or references to them to be exact) so that the memory allocated for them can later be freed automatically by garbage collection when objects are not referenced any more.
EDIT: I'm not sure whether this can be attributed to object creation in the strict sense but it surely happens somewhen between creation and assignment to a variable, even without an explicit assignment (when you create an object without assigning it, the JVM has to auto-release it some time after that as there are no more references).
In C++, only objects created on the stack are released automatically (when they get out of scope) unless you use some mechanism that handles this for you.
1: Depending on the JVM's implementation.
There is one main design difference between constructors in C++ and Java. Other differences follow from this design decision.
The main difference is that the JVM first initializes all members to zero, before starting to execute any constructor. In C++, member initialization is part of the constructor.
The result is that during execution of a base class constructor, in C++ the members of the derived class haven't been initialized yet! In Java, they have been zero-initialized.
Hence the rule, which is explained in paercebal's answer, that virtual calls called from a constructor cannot descend into a derived class. Otherwise uninitialized members could be accessed.
Assuming that c++ uses alloc() when the new call is made, then that might be what they are
looking for. (I do not know C++, so here I can be very wrong)
Java's memory model allocates a chunk of memory when it needs it, and for each new it uses of
this pre-allocated area. This means that a new in java is just setting a pointer to a
memory segment and moving the free pointer while a new in C++ (granted it uses malloc in the background)
will result in a system call.
This makes objects cheaper to create in Java than languages using malloc;
at least when there is no initialization ocuring.
In short - creating objects in Java is cheap - don't worry about it unless you create loads of them.
In Java, for each object, a new copy of instance variables is created which can be accessed using the object reference.
But in case of an instance method, only one copy of it(instance method) exists.
How is this method accessed by various object references?
The byte code (or native code if it's JIT'd) for the method is stored in one location. When the method is called, a pointer (under the hood, aka reference at a higher level) to the instance object is passed as the first argument so the method code can operate on that specific instance - have access to its fields, etc. In order to save space without additional performance cost, the calling mechanism in Java is quite a bit more complicated than C++, especially for interface methods.
Methods and fields are completely different. Methods apply to all instances of the object, but fields are per instance.
One way to think of it:
pretend the method is "global" to all instances, but it is "passed" an instance of the object via the "this" reference.
Methods can change the state of a particular instance, but they themselves are stateless.
Behind the scenes a reference to the object is passed to the method as part of the call. It may be useful to look at Java's reflection classes, Method.invoke() in particular.
From a previous answer of mine:
I'm sure the actual implementation is quite different, but let me explain my notion of method dispatch, which models observed behavior accurately.
Pretend that each class has a hash table that maps method signatures (name and parameter types) to an actual chunk of code to implement the method. When the virtual machine attempts to invoke a method on an instance, it gets the object's class, and looks up the requested signature in the class's table. If a method body is found, it is invoked, providing the original object as a reference called this.
Otherwise, the parent class of the class is obtained, and the lookup is repeated there. This proceeds until the method is found, or there are no more parent classes—which results in a NoSuchMethodError.
If a super class and a sub class both have an entry in their tables for the same method signature, the sub class's version is encountered first, and the super class's version is never used—this is an "override".
the implied reference "this" is passed in to each method, which of course you can reference explicitly
I'm assuming you're meaning on a simplistic level, as in how you actually do the call.
I'm also assuming you're refering to a method that has the static modifier in its signature, ie:
public static int getNum()
{
// code in here
return num;
}
If this is what you mean, and this was part of a class called 'SomeClass', then it would be accessed via the method call SomeClass.getNum(). ie, you put the actual class name before the method.
If this is not what you mean, ignore my answer :)