While you create a user defined class in Java, you do not specify it as extending Object. But still the class is an Object. How does this work? How does javac or the JVM inject all properties of a class to the user defined class?
If you don't actually write extends Object, the compiler inserts it for you.
EDIT: Apparently I caused some confusion about whether there is actually an insertion of code going on. I wasn't entirely sure myself so I ran a little experiment: create the following class in file test.java:
public class test {}
and compile it, then run
javap -c test
to disassemble the bytecode. Look what comes out:
Compiled from "test.java"
public class test extends java.lang.Object{
public test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return
}
So yes, the compiler does actually insert extends java.lang.Object (or the bytecode equivalent) into the class.
All java classes implicitly extend java.lang.Object. From the documentation:
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Here's a link to JVM spec as well:
The standard class Object is the superclass (§2.8.3) of all other classes. A variable of type Object can hold a reference to any object, whether it is an instance of a class or an array. All class and array types inherit the methods of class Object.
Well, this may be a glib answer (my favorite kind), but it probably does it the same way it derives a class if you specify a parent. Isn't that how you'd do it if you were writing the compiler?
It's because all user defined types implicitly inherit from Object.
To say that the JVM "injects" properties or methods into the class makes it sound like it's something the compiler or runtime does after the fact, as though the .class file is different. Really, all that happens is that when the parser sees that you haven't included any base class with extends, it simply pretends you explicitly specified Object. From that point onward, the compiler treats it the same as if you'd typed it out yourself, and the JVM hasn't a clue what you did or didn't specify in the source code.
Related
I'm reading Java Inheritance Docs and got this paragraph, but I don't what is mean of this. Can any body explain?
Excepting Object, which has no superclass, every class has one and
only one direct superclass (single inheritance). In the absence of any
other explicit superclass, every class is implicitly a subclass of
Object.
Edited
Another point related to this question:
And due to Object is superclass, NetBeans show me extra method list when I try to call any Member of class with object reference? All those methods are declared in Object class?
It means that,in java the Object class is the parent class of all the classes by default. In other words, it is the topmost class or the base class of java. All other classes inherit the properties of Object class.
Meaning of implicitly - suggested though not directly expressed.
If samething applied in Java classes. Consider there is a class called Test.
If you write
public class Test {....}
That is equivalent to
public class Test extends Object {....}
Though you didn't write it, it's equivalent to it. You need not to write extends Object manually. Internally JVM treats that your class is extends Object. Since the part after extends is your class, here Object is your super class.
But,
When you write
public class Test extends BigTest{....}
Things changed now. You are telling BigTest is my parent class. That means you are implicitly writing yourself that BigTest is my parent. Interesting part here is though BigTest is your direct Parent class, internally Object also your Parent.
So now you have 2 parent classes. One is BigTest which you mentioned and other is Object. If you didn't mention anything, only Object is your Parent.
Edit :
This is the reason that you will see extra list of method when you will try to call any member of class with object-reference. Those methods are declared in Object class.
why java do this? any feature of this?
Yes. There are benefits of it. Main reason is to reduce the code duplication.
Continue reading here .... Why Object as super class in Java ?
It means that the following two classes are the same:
class MyClass {
}
class MyClass extends Object {
}
If a class definition doesn't specify extends, the class implicitly extends Object.
The Object class comes with the JRE, you use any class without it. Java does this so you can have a reference to any object e.g.
Object o = x;
This works because no matter what x is, it is also an Object.
Note: even int[] class is a sub-class of Object.
I have difficulty in using a generated bytecode class which is loaded by Unsafe.defineAnonymousClass(). I am wondering how to use an object of anonymous class to initiliaze another class (or anonymous class).
Take an example class Callee below for example, its constructor accepts Callee2 as parameter.
Class Callee{
Callee2 _call2;
public Callee(Callee2 callee2){
...
}
}
During runtime, I generated new classes for both Callee2 and Callee, and both new classes are loaded by Unsafe.defineAnonymousClass(). For new Callee, the constructor is also changed to be:
public test.code.jit.asm.simple.Callee(test.code.jit.asm.simple.Callee2.1506553666);
flags: ACC_PUBLIC
Code:
stack=2, locals=3, args_size=2
0: aload_0
1: invokespecial #65 // Method java/lang/Object."<init>":()V
....
8: return
while the generated class name of Callee2 is:
class test.code.jit.asm.simple.Callee2/1506553666
I created an instance of `Callee2/1506553666' and want to create instance of new Callee with it, but fail:
newCls.getConstructor(args).newInstance(objs);
where
args = [class test.code.jit.asm.simple.Callee2/1506553666]
and
objs= [test.code.jit.asm.simple.Callee2/1506553666#39b0a038]
The args[0] is meanless as this class is loaded by anonymous loader (Anonymous classes are not referenced by any class loaders). So it really puzzles me how to pass objects in objs array to a method invocation..
The exception occurs on the invocation of getConstructor (args) with message:
java.lang.NoClassDefFoundError: test/code/jit/asm/simple/Callee2/1506553666
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2483)
at java.lang.Class.getConstructor0(Class.java:2793)
at java.lang.Class.getConstructor(Class.java:1708)
at code.jit.asm.util.ReflectionUtil.adapt2GeneratedObject(ReflectionUtil.java:36)
at code.jit.asm.services.BytecodeGenerator.generator(BytecodeGenerator.java:164)
The exception is clearly for me since the anonymous class is transient to any classloader. But in my case, I do need initialize the new Callee (also anonymous class) by new Callee2 instance (The bytecodes in Callee's constructor will reads Callee2's field members), so is there any workaround to pass new callee2 instance for the new callee's constructor?
Have a look at the signature and documentation comment, which is not available in the standard API documentation as it’s not part of the official API:
Define a class but do not make it known to the class loader or system dictionary.
For each CP entry, the corresponding CP patch must either be null or have the a format that matches its tag:
Integer, Long, Float, Double: the corresponding wrapper object type from java.lang
Utf8: a string (must have suitable syntax if used as signature or name)
Class: any java.lang.Class object
String: any object (not just a java.lang.String)
InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments
… (params:)
cpPatches where non-null entries exist, they replace corresponding CP entries in data
public native Class<?> defineAnonymousClass(
Class<?> hostClass, byte[] data, Object[] cpPatches);
In other words, you may provide an array of the same size as the constant pool of the class you’re going to define. Keep nulls where you don’t want to modify it. Right at the places where your constant pool has a CONSTANT_Class_info representing an anonymous class, you simply pass the associated Class object in the array. So there’s no lookup for the class then, you don’t even have to provide the correct class name in the class bytes.
There are some obvious limitations:
Problem will arise if you have circular dependencies as you need an already existing Class object to patch the pool of another class. Well, for class uses that are known to be resolved lazily, it might work
You can only patch CONSTANT_Class_info to a Class which is sufficient for, e.g. accessing members of that class or creating new instances of it. But it doesn’t help when an anonymous class is part of a signature, i.e. you want to declare a field of that type or use a method having it as parameter or return type. But you may access such methods using the option of patching a CONSTANT_InterfaceMethodref_info entry via a MethodHandle (ahem, once implemented as I guess “NYI” means “not yet implemented”)…
So tha main problem is to understand the class hierarchy of Java.
We need to give an answer to this question:
"Explain whether in Java there is one single class hierarchy (with a single class at the top) or there are many class hierarchies (each with its own top-most class). Explain what consequences this has."
I have no idea about how to answer this question..
From the Object JavaDoc:
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
Edit: Also take a look at the spec.
All objects in java inherit from Object
Its the Object class.
The class Object is a superclass (§8.1.4) of all other classes.
Also check this Oracle docs:
The Object class, in the java.lang package, sits at the top of the
class hierarchy tree. Every class is a descendant, direct or indirect,
of the Object class. Every class you use or write inherits the
instance methods of Object.
The Object class is mother of all java classes.
You can verify the same programmatically.
You will get null in the code below for Super Class of Object
Object.class.getSuperclass(); // returns null
The above test can be done for any other class similarly.
It is the Object Class. Every class is directly or indirectly descendant of Object class which is in java.lang package. Unlike any other parent/child class it doesn't require extends key word to inherit. It's implicit by nature where as you can write explicitly. Java compiler doesn't deny it.
You can use/call methods of object class from any other class and at the same time you can overwrite them to implement in your way.
I have a method that accepts a single parameter. That parameter can be any class A, B, C, or D that all inherit from the same parent class E. I do not know the name of the parent class, however (maybe it's "E" maybe it's "F").
I want my method to accept as a parameter the parent class, so I can pass in a child object (so I only need one implementation of the method).
How do I find the name of the parent class? It is in a jar that I do not have source code access to.
EDIT
Example of what method will look like:
private void processResults(final ???parentClassName??? aParentClassName) {
...
}
Try with Class#getSuperclass()
Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class.
If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned.
If this object represents an array class then the Class object representing the Object class is returned.
sample code:
A.class.getSuperclass().getName()
or
aObject.getClass().getSuperclass().getName()
You can use the javap tool that comes with the JDK.
Suppose your jar file is named unknown.jar and that the package for class A whose parent class you are interested in is com.example.unknown.
You can do this:
javap -classpath unknown.jar com.example.unknown.A
And the output will be something like:
Compiled from "A.java"
public class com.example.unknown.A extends com.example.unknown.E {
public com.example.unknown.A();
}
It will also show you the public API of A. It can show you more information, too, depending on the command line parameters you pass. Use javap -help to see them all.
(Note: You may need to specify additional jars or directories to the -classpath parameter, if unknown.jar has other dependencies.)
If you don't know the superclass / the name of the superclass it's impossible, I think.
If there are only 4 classes, why don't you just create an interface and let your classes A to D inherit them? Might be easier :)
Suppose I have class A
public class A
{
public void method()
{
//do stuff
}
}
Also another class B
public class B extends A
{
public void method()
{
//do other stuff
}
}
Now I have the following statements:
A a = new B();
a.method();
Is this an example of run time polymorphism? If yes, then is no binding is done for the reference a at compile time?
The compiler will tell you that this can't work, because there's no relationship between A and B that will allow you to write A a = new B();
B either has to extend A or both have to implement a common interface with void method() in it.
You could have answered this very quickly by trying it with the compiler. Be an experimentalist - it's faster than forums.
UPDATE:
It works, now that B extends A. The binding that you care about, dynamic binding, is done at runtime. The static compile time type for the variable "a" is class A; at runtime it is dynamically bound to a reference of type B. Yes, I would consider this to be an example of polymorphism.
I was waiting to put my answer to another post, into a more correctly classified problem. Your question fits the concept, I've tried to explain in detail. but, since I don't know how link answers, I'll just copy/paste the complete script here .... Kindly go through it, you'll understand everything that there is to understand about your problem, you've asked
let's say compiler has to resolve a call like this : *
A a = new AA(); // Assume AA to be some subclass of class A
a->someFunc(); // and we're invoking a method "someFunc()' on a
*.
Now, compiler will go over following steps methodically.
1.) Firstly, compiler knows the declared type of variable a, so it will check whether the declared type of object a (lets call this, class A for time being), have a method with the name someFunc() and that it must be public. This method could either be declared in class A, or it could be a derived method from one of the base class(es) of class A, but it doesn't matter to compiler and it just checks for it's existence with it's access specifier being public.
Needless to say any error in this step will invite a compiler error.
2.) Secondly, once the method is validated to be a part of the class A, compiler has to resolve the call to the correct method, since many methods could be there with same name (thanks to function overloading). This process of resolving correct method is called overloading resolution. Compiler achieves this by matching the signatures of the called method with all the overloaded methods that are part of the class. So, of all the someFunc() s only the correct someFunc() (matching the signatures with called method) will be found and considered further.
3.) Now comes the difficult part, It may very well happen that someFunc() may have been overridden in one of the subclasses of the class A (lets call this class AA and needless to say it is some subclass of A), and that variable a (declared to be of type A) may actually be referring to an object of class AA, (this is permissible in C++ to enable polymorphism). Now, if the someFunc() method is declared to be of type virtual, in base class (i.e. Class A) and someFunc() has been overriden by subclass(es) of A (either in AA or classes between A and AA), the correct version of someFunc() have to be found out by the compiler.
Now, imagine you're the compiler and you have this task of finding whether the class AA has this method. Obviously, class AA will have this method since, it is a subclass of A and public access of A in class A has already been validated in Step 1 by the compiler !!! . But Alternatively, as mentioned in previous paragraph, someFunc() may be overriden by class AA (or any other class between A and AA), which is what compiler needs to catch. Therefore, you (since, your'e playing the compiler) could do a systematic check to find the bottom-most (lowest in the inheritance tree) overridden method someFunc() starting from class A and ending at class AA. In this search, you'll look for same method signatures as was validated in overloading resolution. This method will be the method which will be invoked.
Now, you may be wondering, "What the heck", is this search done everytime ? ... Well, Not really. The compiler knows the overhead of finding this everytime, and as such, maintains a data-structure called Virtual Table for every class type. Think of virtual table, as mapping from method signatures (which are publicly accessible) to the function pointers. This virtual table is made by compiler during compilation process and is maintained in-memory during program execution. In our example, class A and class AA will both have their own virtual tables. And when compiler has to be find someFunc() in class AA (since actual object pointed by variable a is of type AA), it will simply find the function pointer through the virtual table of Class AA. This is as simple has hashing into the table and is a constant time operation.
Regards
AViD
The code example you've given isn't legal, so I guess the answer is that it's not a kind of polymorphism.
You can't assign a class to a variable of an unrelated type like that. I'm guessing that you might be intending for B to derive from A?
Is this an example of run time polymorphism?
As of the edit: yes that would be runtime polymorphism, since which method is actually executed depends on what is assigned to a.
Edit:
If method() would be static, then calling a.method() would always result in the version of A being called. However, you'd then just write A.method() and if you don't do that any decent IDE would warn you about that (because it might be misleading to call a static method on an instance).
End Edit.
Compile time polymorphism would be the overloading mechanism, i.e. the compiler decides whether to use someMethod(Number) or someMethod(Integer) depending on what it knows about the parameter that is passed (if you pass a Double or just a Number it would be the first one, if you pass an Integer it would be the second).
If yes, then is no binding is done for the reference a at compile time?
What do you mean exactly? Note that the type of a will be A so you can assign everything that extends A at runtime. The compiler will just complain if the assigned value is not an A (you might trick the compiler with a cast, but this is just evil and if this breaks your program, you have been warned ;) )
It should be
public class B extends A {
public void method()
{
//do other stuff
} }
If it were compiling, it would be the B::method() that would be called. (only if you changed your code to make the B class inherit the A class).
In this case your use your object like it was only an A, but if some methods are overidden in B, then these methods are called, instead of A's methods.