Static binding and dynamic binding with no methods - java

I had an exam in my college on objected-oriented programming. One of the questions was about static binding and dynamic Binding.
The question was as follows:
Shape s; if(i==1) s = new Point(1,2); else s = new Rectange(10,20); //this is dynamic binding.
YES/NO
it's not my answer btw.
My teacher said the answer is "no" because it's static binding.
As I know static binding and dynamic binding happen only when I call methods. I read all the StackOverflow questions and a lot of blog posts about this topic and the only answer I can come up with is that there is dynamic binding.
Any explanation will be appreciated.

"binding" just means you're associating a name with an object, so there is binding going on here.
This is dynamic binding, see the wikipedia article:
The binding of names before the program is run is called static (also "early"); bindings performed as the program runs are dynamic (also "late" or "virtual").
An example of a static binding is a direct C function call: the function referenced by the identifier cannot change at runtime.
But an example of dynamic binding is dynamic dispatch, as in a C++ virtual method call. Since the specific type of a polymorphic object is not known before runtime (in general), the executed function is dynamically bound.
Even though the posted code predetermines what s gets set to by setting i, what makes this dynamic is that methods called on s will get resolved at runtime.

No. It's dynamic binding.
The value of i variable is not known at compile time. Depending on value of i variable at run time, Shape has been set. As Nathan Hughes suggested, the methods called on Shape are resolved at runtime, which makes it late dynamic binding.

Related

Why does Java's Dynamic Proxies need reflection?

Java's Dynamic Proxy Docs describe these constructors as the following:
A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class.
Now, while everything in this sentence is accurate. All of this information is in fact present at compile time. In Java, when you are creating a proxy, you specify the exact interface you want to proxy in your code.
Now the first thing that really confuses me, is why the byte code here needs to be generated at run time? All of this information is present at the compile time... (and you don't even have to deal with type erasure)
P.S: I am not sure if this is still the case, basing this on a quite dated accepted answer here: How does Java's Dynamic Proxy actually work?)
The next step in getting this work is the type checking/type inference. I am not sure how Java actually handles this, but you need to be able to use Proxy<A> interchangeably with A. In order to pull this of you need the following:
∀ method m ∈ A, m ∈ Proxy<A>
Which means that
you need your proxy to have the same structure
you need some kind of delegation (i.e. dynamic dispatch).
Once you start writing out the inference rules, this gives us something very familiar. Structural Typing
Now Java doesn't have structural typing but one could easily add the few inference rules (i.e. Typescript) especially given Java has boxed primitives (Scala for example doesn't which makes it very difficult to introduce structural inference).
The Actual Question
Reflection is hard, not safe and not super performant. My question is why and how Java's proxies use reflection? It seems like most of this functionality could be implemented using other features already present in the language.

How to detect java local variables by an interface type and then find methods called on them?

I have some (maybe) strange requirements - I wanted to detect definitions of local (method) variables of a given interface name. When finding such a variable I would like to detect which methods (set/get*) will be called on this variable.
I tried Javassist without luck, and now I have a deeper look into ASM, but not sure if it is possible what I wanted.
The reason for this is that I like to generated a dependency graph with GraphViz of beans that depend on the same data structure.
If this thing is possible could somebody please give me a hint on how it could be done? Maybe there are other Frameworks that could do?
01.09.2015
To make things more clear:
The interface is self written - the target of the whole action is to create a dependency graph in the first step automatically - later on a graphical editor should be implemented that is based on the dependencies.
I wonder how FindBugs/PMD work, because they also use the byte code and detect for example null pointer calls (variable not initialized and method will be called on it). So I thought that I could implement my idea in the same way. The whole code is Spring based - maybe this opens another solution to the point? Last but not least I could work on a source-jar?
While thinging about the problem - would it be possible via ASM/javassist to detect all available methods from the interface and find calls to them in the other classes?
I’m afraid, what you want to do is not possible. In compiled Java code, there are no local variables in the form you have in the source code. Methods use stack frames which have memory reserved for local variables, which is addressed by a numerical index. The type is implied by what instructions write to it and may change throughout the method’s code as the memory may get reused for different variables having a disjunct scope. The names on the other hand are completely irrelevant.
When bytecode gets verified, the effect of all instructions to the stack frame will get modeled to infer the type of each stack frame slot at each point of the execution so that the validity of all operations can be checked. Starting with class file version 50, there will be StackMapTable attributes aiding the process by containing explicit type information, but only for code with branches. For sequential code, the type of variables still has to be derived by inference.
These inferred types are not necessarily the declared types. E.g., on the byte code level, there will be no difference between
CharSequence cs="foo";
cs.charAt(0);
and
String s="foo";
((CharSequence)s).charAt(0);
In both cases, there will be a storage of a String constant into a local variable followed by the invocation of an interface method. The inferred type will be String in both cases and the invocation of a CharSequence method considered valid as String implements CharSequence.
This disproves the idea of detecting that there is a local variable declared using the CharSequence (interface) type, as the actual declared type is irrelevant and not stored in the regular byte code.
There are, however, debugging attributes containing information about the local variables, see the LocalVariableTable attribute and libraries like ASM will tell you about the declarations if such information is present. But you can’t rely on these optional information. E.g. Oracle’s JRE libraries are by default shipped without them.
I don't sure I understood exacly what you want but .
you can use implement on each object ,
evry object that have getter you can implement it with class called getable .
and then you could do stuff only on object that have the function that you implement from the class getable .
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

rJava generics type

I have been playing with rJava package, but since it seems that rJava is not aware of Java generic types, I have difficulties creating java object with generic type parameters. If I have a java class like:
public class A<T> {
private B<T> b;
public A(B<T> b) {
this.b = b;
}
}
I would like to create an A object from R session using .jnew() by passing a B object already created (with instantiated type parameter), but rJava always gives error:
java.lang.NoSuchMethodError: <init>
Is there any work around for this?
There are a lot of moving parts in this question. Digging through the documentation for the various parts, I think that you need to do this on the line that broke:
gesinstance = .jnew("edu/cmu/tetrad/search/Ges", .jcast(dataset, "edu/cmu/tetrad/data/DataSet"))
The key difference being the call to .jcast on the second argument. (I don't have R installed, so I could not test this - If it doesn't work, I will update my answer based on any feedback you can provide on new error messages.)
So then the question is "why that?" The answer seems to be:
On the Java side, DataReader.parseTabularData returns an object with type DataSet as you noted, but DataSet is an interface not a class. That necessarily means that the actual object returned is of some class that implements the DataSet interface.
For reasons that aren't immediately clear to me, the rJava package does not really handle polymorphism well. It requires that you call methods with an "exact" signature match to the objects that you are passing. In this case, you will need to "up-cast" from whatever specific class you got to the interface DataSet. See the documentation for .jnew (https://www.rforge.net/doc/packages/rJava/html/jnew.html), especially for the arguments that they denote by "...". This refers you to the corresponding part of the documentation for .jcall (https://www.rforge.net/doc/packages/rJava/html/jcall.html), when then explains the requirement to call .jcast (https://www.rforge.net/doc/packages/rJava/html/jcast.html) with some examples.
The error that you got java.lang.NoSuchMethodError: <init> was telling you that the JVM could not find the constructor that you called. This was mysterious looking in the example that you posted in the comments. (It might be good to edit your question, by the way, and include that information up there for posterity.) The code certainly looks right, and, knowing Java, I intuitively expected the interface to respect the polymorphism of the Java. Given that (for whatever reason), the interface to R does "exact" type matching without considering inheritance, it's clear that it will not find a constructor due to reason #1 above.
Finally, I didn't actually encounter any Java classes using generics in my limited exploration of Tetrad. As it turns out, that was a complete red herring though. Should it be an issue in the future, you'll probably want to check out "Type Erasure" (https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). If you were interfacing between Java and C, C++, Fortran, any language that Java considers "native," then you'd deal with the generics in the native code by dealing in the type-erased forms. The rJava interface may be different though, since this seems to fall into the same general type of structure that tripped you up on your current problem. (Maybe worthy of its own bounty later!)

early binding late binding is it same as runtime and compile time?

When we create object inside a function is that object created at runtime?
What are the things happen? created? at compile time and at runtime?
Is early binding and late binding also means compile time and runtime?
What is dynamic linking static linking? is it right to think compile time when I hear static? damn I so confused?
sorry guys I know my english is bad and also please make your answers and examples beginner friendly as possible.
Early binding is like going getting tomatoes from the refridgerator and putting them on the table before you starting cooking the soup.
Late binding is starting cooking the soup, and when you need tomatoes, then you go to get them from the refridgerator.
Cooking the soup is run time.
Getting the knife,spoon and saucepan ready is compile time. (It doesn't involve tomatoes.)
Ok here's a pseudo coded explanation :
late binding :
... get :
if (myvar is null) myvar = new object;
return myvar
early binding
myvar = new object;
... get :
return myvar
When we create object inside a function is that object created at
runtime?
What are the things happen? created? at compile time and at runtime?
That depends on what you mean by "object." If you mean a class instance, then yes it will be created at runtime on either the stack or the heap. Statically allocated objects, like strings or types explicitly declared as static, will be created at compile-time in the data segment. Static variables live for the life of the program.
Is early binding and late binding also means compile time and runtime?
From Wikipedia:
With early binding the compiler statically verifies that there are one
or more methods with the appropriate method name and signature. This
is usually stored in the compiled program as an offset in a virtual
method table ("v-table") and is very efficient. With late binding the
compiler does not have enough information to verify the method even
exists, let alone bind to its particular slot on the v-table. Instead
the method is looked up by name at runtime.
In a nutshell, in early binding the compiler looks up the method and its offset in the symbol table, so that information must be available, whereas in late binding that can't be done, and the runtime must look it up. Note that late binding is very different from dynamic dispatch, though they are often used synonymously, in that the latter refers to using a dispatch table or "vtable" to store pointers to a method's implementation, which may be overridden.
What is dynamic linking static linking?
Basically this is difference between including referenced files or "libraries" in the final executable (static) and placing them into the program image at runtime. Obviously, the former adds unnecessary size to the executable, but (1) you never have to worry about dependency issues and (2) program start up is more efficient. On the other hand, dynamic linking (1) saves spaces and (2) allows library updates to occur in one place.
Nothing in Java is statically linked, but it is statically bound. "Static" means the compiler identifies the exact description of the function to be called: class name, method name, argument types. It does NOT determine its address in memory. That's the difference between static binding and static linking, and this means that it is still not known at compile time what code will be executed when you call a static method. It depends on what's in the .class file that the JVM loads at runtime. Java statically binds all calls to static methods -- hence the keyword. It also applies static binding to private methods, since they cannot be overridden. A similar argument applies to final methods.
Dynamic binding means that the compiler decides everything like in the static case, except for the class which contains that method. The exact class is determined at the last moment before calling the method, relative to the object on which the method is being called. Object.equals is such a dynamically bound method. This means that the same line of code can call a different method each time it is executed.
Early binding == static binding; late binding == dynamic binding. These are synonyms.
early binding is a assignment of value to design time where a late binding is a assignment of value to runtime
There is only difference between run time and design time it must show the value of assignment .
For example:
//early binding
myvar =new myvar();
// get
retutn myvar

What is binding of methods?

For my class, comparative languages, there is an example exam and one of the quesitons is: "What is binding of methods?"
So, what is it?
The question goes on to ask what is static versus dynamic binding which, the difference here is compile time versus run time.
This refers to the process that takes a method name and parameter types (eg, toString()) and finds the actual method that should be called (finding the right method from the appropriate type or base type and performing overload resolution).
Use google for these kinds of questions.
http://geekexplains.blogspot.com/2008/06/dynamic-binding-vs-static-binding-in.html

Categories

Resources