Instance Method call in Java - java

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 :)

Related

Instance and Static Methods in Java

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.

To get the hashCode() of the object that calls a specific method in Java

What I'm trying to is to get 'hashCode()' value of the object that calls a specific method in Java. For example,
public class Caller {
public void aMethod() {
Callee calleeObj = new Callee();
calleeObj.aSpecificMethod();
//do something
}
}
What I want to know is Caller's hashCode() value which calls calleeObj.aSpecificMethod() during the runtime. It is for drawing an Object diagram like below.
As a constraint, I only can modify '.class' files using bytecode instrumentation techniques.
To do that, I've tried Javassist library to instrument inside Callee.aSpecificMethod() but this way cannot get the caller's object. The reason seems obvious because instrumented code on 'Callee.aSpecificMethod()' only can access codes on Callee class, not Caller class.
Is there any way to capture the hashCode() value of caller's object using Javassist? I'm considering ASM 5.0 also, but using ASM 5.0 is the last option because I've built many code based on Javassist until now.
As said by others, there is no way of the invoked method getting hands on the caller object, but so far, nobody pointed you to the reason why this will never be possible:
The big misconception about your request is that you assume that there has to be a “caller object”. But there is no such thing. Your method might get invoked by static methods, e.g. right from the main method of an application, but also from class initializers or from constructors, even during the super constructor invocation, in other words, at places, where an object exists in the context of the invocation but hasn’t fully constructed yet, hence at a place where hashCode() can’t be invoked.
If you haven’t considered these gaps in your idea, you shouldn’t start using Instrumentation to alter the caller’s byte codes. It’s very unlikely that you will produce correct code. Even at places where an instance exist at the call cites, that instance doesn’t need to be available, nor does hash code calculation. What if you method get invoked from another object’s hashCode method?
Besides practical obstacles, the big question is, why do you think you need the “callers” hash code? What ever you intend to do with it, it can’t be right. Think of the following code:
public class Caller {
public void aMethod() {
Callee calleeObj = new Callee();
new Thread(calleeObj::aSpecificMethod).start();
}
}
Whose hash code are you interested in? Of the instance of the anonymous class generated at runtime? Of the Thread instance invoking the run method of that anonymous class? Or of the Caller instance which won’t be on the call stack at all, when your method get invoked?
You have to pass either the calling object or its hash code as a parameter to the method.

Why is a static method considered a method?

I'm writing an explanation for some code for a course, and have been accidentally using the words method and function interchangeably. I decided to go back over and fix the wording, but ran into a hole in my understanding.
From what I understand, a subroutine is a function if it doesn't act on an instance of a class (its effect is restricted to its explicit input/output), and is a method if it operates on an instance of a class (it may carry out side effects on the instance that make it impure).
There's a good discussion here on the topic. Note that by the accepted answer's definitions, a static method should actually be a function because an instance is never implicitly passed, and it doesn't have access to any instance's members.
With this is mind though, shouldn't static methods actually be functions?
By their definition they don't act on particular instances of a class; they're only "tied" to the class because of relation. I've seen a few good looking sites that refer to static subroutines as "methods" though (Oracle, Fredosaurus, ProgrammingSimplified), so either they're all overlooking the terminology, or I'm missing something (my guess is the latter).
I'd like to make sure I am using the correct wording.
Can anybody clear this up?
This quote from 8.4.3.2 may help:
A method that is declared static is called a class method.
A method that is not declared static is called an instance method [...].
Class methods: associated with a class.
Instance methods: associated with an instance.
Java just wants you to "think object-oriented". Also, static methods have access to a surrounding scope which may include state. In a way, the class is like an object itself.
The simple answer is that when Java decided to call everything a "method", they didn't care about the distinction between a function and a method in theoretical computer science.
Static methods are not exactly functions, the difference is subtle, but important.
A static method using only given input parameters is essentially a function.
But static methods may access static variables and other static functions (also using static variables) so static methods may have a state which is fundamentally different to a function which are by definition stateless.
(ADDENDUM: While programmers are often not so strict with using "function" as definition, a strict function in computer science can access only input parameters). So defining this case of accessing static fields it is not valid to say that static methods are always functions.
Another difference which justifies the usage of "static method" is that you can define in C derivates global functions and global variables which can be accessed everywhere. If you cannot access the class which contain static methods, the methods are inaccessible, too. So "static methods" are limited in their scope by design in contrast to global functions.
In Java, a user-defined class is actually an instance of a subclass of java.lang.Class.
In this sense, static methods are attached to an instance of a conceptual class: they are attached to an instance of a subclass of java.lang.Class.
With this in mind, the term "class method" (an alternate name for Java's static methods) begins to make sense. And the term "class method" can be found in many places: Objective C, Smalltalk, and the JLS -- to name just a few.
In computer science function clearly maps to a static method. But "method" of a class is a bit generic, like "member" (field member, method member). There are wordings like
Data members and method members have two separate name spaces: .x and .x() can coexist.
So the reason is, that as the philosoph Ludwig Wittgenstein said, Language is a tool with different contexts. "Method" is a nice moniker in the citation above to categorize a "member".
Your thinking is right and it makes sense. It's just not established terminology in the Java community. Let me explain some internals that can help understand why the terminology subsists.
Java is a class based object oriented language. A method is always member of a class or instance (This is a general statement valid for other programming languages too). We think of class and instance being both objects.
Instance method (dynamic)
You cannot invoke this method from a class directly, you have to create an instance. Each instance references that method. You can overwrite a method definition with the exact same method signature (when subclassing), i.e. the reference points to a different method (which has the same signature, but can have a different method body). The method is dynamic.
Class method (static)
You only can invoke this method from the class directly, i.e. you don't need to create an instance of that class. There is only one global definition of that method in the whole program. You cannot overwrite the exact same method signature when the method is declared static, because there is only one definition valid for the whole program. Note that the method is member of the class object itself, the instances have all the same unique (and fix) reference to that method.
Here is another take on the terminology, using Scala as a mnemonic:
In Scala you have objects, which are singleton instances of an implicitly defined class 1.
Per your definition, we can call these subroutines belonging to the object methods, as they operate on a single instance of the class.
Additionally the object will also define class A, and create all of the methods in object A as static methods on class A (for interfacing with Java) [2].
Therefore we can say that the static methods of Java class A access the same members as the Scala singleton instance, which per your definition then deserve to be called (static) methods of class A.
Of course, the main difference is - method can use static fields, not only method parameters.
But there is additional one - polymorphism!
Results of evaluation Class A.doTheSameStaticMethod() and ClassB.doTheSameStaticMehod() will be depends of class. In this case function is impotent.
Each class has an object to represent it that is an instance of a subclass of the Class class. Static methods are really instance methods on these objects that are instances of a subclass of Class. They have access to state in the form of static fields, so they are not restricted to being just (stateless) functions. They are methods.

Object creation/initialization semantics in Java

I'm a die-hard C++ fan who is picking up Java for Android apps. In C++, the canonical way of creating and initializing an object would be to totally intialize it in the constructor:
class Message {
string payload;
int client;
// etc.
public:
Message(string payload, int client)
: payload(payload)
, client(client)
{}
};
This seems possible to do in Java. It gets a bit uglier because I want to make certain members const (the best Java can do is final), but generally I can figure it out.
But now I'm running across libraries such as FreeHEP-XDR, whose XDRSerializable interface specifies a signature:
void read(XDRDataInput in);
This function, which will be implemented by Message, is obviously not a static instantiator, as it returns void. The Message object would have to be fully constructed, probably with a default constructor, before calling this function. This bothers me: the caller can easily pass an XDRDataInput in the constructor, and anyway I'll be initializing the object twice (once in the default constructor, again in read). Most egregiously, implementing this requires me to drop my final modifier from certain Message data members, because they'll be modified after the constructor is finished!
Is this par for the course for Java? What's the object protection, creation, and initialization paradigm?
Well, the main issue with constructors is that they are not polymorphic. Meaning that the client whose invoking such constructors needs to always know what concrete type is she building. By deferring initialization and construction you can, pontentially, take the decision of which concrete instance you want to create at point a and polimorfically initialize it at point b.
Also, java does not have any way to force implementors of a certain contract (an interface, by example) to define a certain constructor. So it is either adding a weak condition to the interface contract (like a comment in the javadoc saying that implementors should provide a constructor that receives XHRDataInput) or adding a initialization method to the interface and forcing you to provide an empty constructor instead (which is by far a more common practice, probably inherited from the JavaBeans "specification").
Having said that I will also state: Yes it totally breaks your "final" semantics. You can add a check in your "read" method that checks over a certain condition and ensure that your object is initialized only once (throwing an Exception if read is invoked twice), but that is totally up to you.

Question about constructors in Java

I have few questions regarding Java constructors
Can a constructor be private? If yes then in which condition?
Is a constructor a method or not?
If a constructor does not return anything then why we are getting a new Object every time we call it?
What's the default access modifier of a constructor if we do not specify.
Edit
The answers for 1 & 3 are very clear. I'm still not sure about 2 & 4 since I'm getting different answers for them.
Can a constructor be private? If yes then in which condition?
Yes. There are no conditions. Of course, no one except the class itself can call it then.
This is actually a frequent pattern: Have a static getInstance() and keep the constructor private.
There can also be private constructors that the public constructors internally call.
Constructor is a method or not?
Hmm. I say "no". At the very least, it is a "very special kind of" method. In what context exactly? The terminology is less important than what you are trying to do.
If constructor does not return anything then why we are getting a new Object every time we call it.
The new operator returns something (the new instance).
Whats the default access modifier of a constructor.
Same as for methods. Package-private.
If you do not specify any constructor, the class gets a default constructor, which takes no arguments, does nothing except calling the parent constructor and is public.
Yes, in any case. However, if all constructors for a class are private, that means that the class cannot be directly instantiated. You will need to use something like the Factory Pattern to create instances of the object.
Yes, the constructor is a method.
A better way to think about it is that the new operator returns the object and in the process of creating the object, calls the constructor. Another way to think about it (although this is only a way to think about it, it isn't technically correct) is simply that the return type is implied by convention. A good place to read more about this is to read about new in the context of C++. The constructor's role is not to create the object but rather to initialize the memory contained within the object.
Default access for a constructor in Java is package private just like any other method. (One such source: http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers and from the horse's mouth: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
Yes, constructors can be private. This is done when you want tighter or alternate control over instance creation such as with factory methods or with a pattern such as a Singleton.
It is a method but it is not called directly. It is a special type of method invoked on your behalf when you create a new object.
Constructors don't return anything, they create new objects.
The default is package private. So public to any class within the package but not visible to code outside of the package.
Thoughts on Tomcat performance and scalability: This is a highly variable situation based on your server hardware and types of requests and of course the quality, efficiency and memory footprint of the code serving each request.
Your lower bound on concurrent requests was 500. Consider that you probably want to create a thread for each request and given a 1MB stack per thread you're looking .5 GB just for thread stack space. And this is before heap memory and the performance overhead of allocating that many threads. I think that if need to handle that many requests at a time you might want to consider a more heavy duty server like JBoss.
A constructor can be declared private for any class.
A constructor is a special method that returns an instance of the class it belongs to, therefore you do not need to specify a constructors return type.
Package private is the right answer as pointed out below.
Yes -- factory instance singletons often use this pattern, to force users to init their class via static factory method.
Yes, it's a method
Because that is what a constructor does - it constructs. (it's assumed the result of construction will be returned)
same as methods
With regards to your Tomcat question, it depends on which version of Tomcat, which IO model it's using (e.g., NIO versus historical network IO modules), and your configuration. Single Tomcat's can process hundreds of requests at a time, although the concurrency is tune-able (each request will be handled by a distinct thread or thread from a pool).
The default access modifier of a constructor is CLASS ACCESS MODIFIER,
If a class is public , then access modifier of a constructor is public. If the class is default , then constructor is also default.
Constructor can be created as a private in any case.
Constructor is a special type of method which can be automatically called when we
are creating object for the corresponding class.
Constructor does not contain any return values. It just create new objects. Should not provide any return type for constructor.
The default access specifier of the constructor is public
Yes.
Yes.
because a constructor is called by new. What returns the object is the new, the constructor simply sets up the internal state.
Public.

Categories

Resources