Java Object superclass - java

I have a weird Java question:
As we know:
All Java classes extend java.lang.Object
All Java classes cannot extend itself
Then, java.lang.Object must extend java.lang.Object, which is itself, therefore, it should be impossible. How is Object implemented in Java?

Object is an exception to the first rule, and has no superclass. From JLS3 8.1.4:
The extends clause must not appear in the definition of the class Object, because it is the primordial class and has no direct superclass.
You can also try it out with reflection:
Object.class.getSuperclass(); // returns null

You'd be better off thinking of this as:
All java classes must implement the interface implied by the methods in java.lang.Object.
The concrete class java.lang.Object provides default implementations of these functions.
All other java classes are derived from the object java.lang.Object and may choose to use or override the default implementations of the methods.
The two main points are: all the classes must implement the implied interface and the Java language spec gives you (forces upon you?) default implementations for these methods for free.

Object does not extend itself. It is the superclass for all other objects in the Java language. Think of it as being the level-0 (or root) class of all the objects in the Java API tree - including any objects you create as well.
I also just want to point out that your question is proven impossible by rule #2 that you posted. Your logic used to justify your question only takes #1 into account and is therefore extremely flawed.

Related

Why are there no subclasses of java.lang.Class?

java.lang.Class defines multiple methods which only apply to a certain type of class, e.g.:
getComponentType: Only relevant for arrays
getEnumConstants: Only relevant for enums
So why is there, for example, no ArrayClass which defines the getComponentType method instead?
This appears to be more or less a design choice. Since i did not design this language, i cannot answer it with certainty, but i'll try to explain potential reasons for this.
So why is there for example no ArrayClass which defines the getComponentType method instead?
The trick to understanding this is, that the java.lang.Class class is not a direct equivalent to the class you are coding. This specific class is only used to represent the created class at runtime (for example: for the use of reflections).
As from the Java-Doc of the Class (here from Java 7):
Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
You are writing custom classes, if you write your code, which means that your created code is the class. If you create a class called the ArrayClass, this is your class. The java.lang.Class class is then only usable at runtime to analyze the class of this specific Object.
For the design in Java, two more layers of complication are added.
First: You can analyze every object, which is a subtype of java.lang.Object. The method getClass is defined here. This means that you are able to introspect any object for any specific detail. If the specific type of the Object is not an enum for example, the class returns null upon calling getEnumConstants. If you had specific sub-types of the java.lang.Class, you would have to cast the instance before introspecting it, which would make it more annoying to work with.
Second: The java.lang.Class object, representing your type is created lazy, within the ClassLoader. Upon referenzing a specific type, the ClassLoader checks whether or not the Class is already loaded and if not, loads it. It then creates the java.lang.Class-Objects, which represents this specific Type. This class-object can then be used, to create instances of your type.
If the java language had different subtypes for the java.lang.Class, the ClassLoader would have to instantiate the correct subtype of the Class, corresponding to what would be needed. If you where able to create custom subtypes of the java.lang.Class, this would get out of hand quickly. How is the ClassLoader supposed to know which Class-instance is connected to your Type? Would you have to write specific Class-instances and somehow mark your created type to use that Class-instance? You could imagine something like this:
public class MyType extends ... implements ... type MyClassInstance
But then, how do you fill up custom fields within your custom java.lang.Class instance? Those complications may be the reason, that the java.lang.Class has a generic type, representing the connected Type. Event though there are a million possible solutions to those complications, there still might be an argument to be made for usability and robustness.
As Oracle point out in there Design Goals of the Java Programming Language:
The system that emerged to meet these needs is simple, so it can be easily programmed by most developers; familiar, so that current developers can easily learn the Java programming language; ...
As much as one would love to see something like this within the language, this feature would make it way more complicated, since it would allow developers to change the behavior of the newInstance method for example. You could introduce an Exception within this Method and one might think, the constructor threw an Exception, even though it did not. This goes into the same (or a similar) direction as Why doesn't Java offer operator overloading?, with that, you are essentially overriding the new keyword.
The Class currently is final (likely because it is a core language construct). This prohibits subtypes of java.lang.Class. If the class should receive subtypes, it has to loose final which means anyone could override any specific detail for a class. Calling getClass could result in any unknown type, that could do anything.
With that, we now only have specific subtypes of classes, we still cannot access them. To do this, we have to do one of the following:
Either add a generic type to the Object like this (i don't want to start a debate about super or extends, this is just an example):
public class Object<T extends Class> {
public final native T getClass();
}
This is required because we want to have certain classes connected to certain objects. With this however, we are not specifying how to instantiate the class. Normally a class is instantiated through the ClassLoader. Again from the JavaDoc:
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
This would no longer be viable, except we require certain aspects like a private constructor. Also, we had to provide every custom Class as native C++ code.
The other possibility would be, to define the getClass method in implementations something like this (this code has different generic based issues, but again, just an example):
public class Object {
public <T extends Class<?>> T getClass() {...}
}
public class MyType {
public MyClass getClass() { return new MyClass(); }
}
Which would open the door to more complicated issues introduced earlier. You could now do work in here, that you are not supposed to do. Imagine a InvocationHandler for example. The other issue with this is that now the developer has the freedom to decide whether or not a Class is instantiated only once or multiple times, which would break for example the Class-Based-Programming and of course some aspects of the Java-Language.
Even though i cannot answer with certainty, i hope this helped a bit.

How does the java compiler check if all methods in an interface were implemented?

If I declare that my object implements an interface, but fail to implement those methods, when I compile my code, I get a compiler error. How does the java compiler know that I haven't implemented all of the methods of an interface?
How does the java compiler know that I haven't implemented all of the methods of an interface?
It knows all methods that your class has implemented because it has found and analyzed them during the compilation.
It knows all of the methods that were defined in all of the superclasses and interfaces of your class because:
it has either just compiled their source code, or loaded their ".class" files, and
it has analysed the interfaces / classes and figured out which methods need to be implemented by your class.
Then it compares the two sets of methods. (Note that the methods don't need to be exactly the same. For example, the actual method could return a subtype of the return type of the method in the interface. The set comparison needs to take account of that.)
(Actually, that is just one approach to doing this check. An actual Java compiler might do the checking a bit differently.)

Interface with no methods

Why do Java introduces some interface which has no methods defined in it? For example Cloneable, Serializable, Type and many more.
Second thing : In Class.class package there is one method defined registerNatives() without body and is called from static block but Class.class is not abstract but is final. Why so?
and Why Java need some method without body to be called from static block.?
Why do Java introduces some interface which has no methods defined in it?
This are called Tagged or Marker interface. These are not used for any use or operation. These methods are used to tag or marking a class. So that you can determine whether someclass is a child of those classes.
about the second question
If you look closely you can see the declaration is
private static native void registerNatives();
So registerNatives is a native methods.
So what is native methods. If you see this so question
The method is implemented in "native" code. That is, code that does
not run in the JVM. It's typically written in C or C++.
Native methods are usually used to interface with system calls or
libraries written in other programming languages.
So these methods are loaded from native codes. So you don't need to declare the body of the methods but still they are not abstract as they have their implementation from native codes.
Marker interface is used as a tag to inform a message to the java compiler so that it can add special behavior to the class implementing it. Java marker interface has no members in it.
The purpose of Marker interfaces is to force some kind of functionality in the classes by providing some functionality to a class if it implements the marker interface.
Read Java Marker Interface also see What is the use of marker interfaces in Java?
For the first one you are actually asking for a Marker Interface. Marker Interfaces are by design not supposed to add anything to behavior but support only polymorphic transformation of the object. e.g. Serializable makes an object capable of streaming across JVM boundaries. Marker interfaces follow the 'universal type substitution' philosophy.
For second one, you are actually asking for JNI. Java doesnot implement all its code in Java form. I mean in classes and code that follow Java syntax. Some time or the other you need to drill down to the native platform API to implement something for that API. e.g. sockets and TCP communication. It is this feature of Java that actually makes it platform independent. The JVM runtime is platform dependent as it uses platform based native methods and dll or .so libraries to implement and integrate with the platform. We as programmers call the high level Java SDK API calls.
One of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.
Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:
java.lang.Cloneable
java.io.Serializable
java.util.EventListener
Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose. For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o:
SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());
If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type "Cloneable." Hence, even though Cloneable is an empty interface, it serves an important purpose.
registerNatives()
native method are implemented in JVM itself.
What does the registerNatives() method do?
Why Java need some method without body to be called from static block.?
This is called from static block because we need to call this method when classes are loaded and not when it's instance is created.

Multiple inheritance in Java or not? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
It is said, that Java language support single inheritance only.
However how is it possible to inherit from Object and from any other class at the same time? Isn't that a multiple inheritance.
Secondly, what for do we need to inherit all 11 Object methods? I could hardly imagine why do I need it them in I/O e.g.
Finally JDK 8 is going to offer us default methods realization in interfaces and if which would probably cause multiple inheritance in Java.
What if interface A provides method a() with default realization and interface B provides also a() method with another default realization and our custom class C implements both interfaces and rely on default realization - wouldn't that be Diamond of Death ?
However how is it possible to inherit from Object and from any other
class at the same time? Isn't that a multiple inheritance.
No this is not what happens. Not all classes directly extend from Object class. But only the class at the top level of inheritance hierarchy extends from Object class(implicitly). Rest of the classes lower in the hierarchy, extends from the Object class through the super classes. And, this is what we call multi-level inheritance.
So, consider the below hierarchy: -
class A { }
class B extends A { }
In the above case, class A is equivalent to class A extends Object.
Secondly, what for do we need to inherit all 11 Object methods? I
could hardly imagine why do I need it them in I/O
I suspect you meant override when you say inherit. You don't need to override any method of Object class. It's just on your requirement, whether to override any method or not. For e.g.: - You would often want to override equals() method, so as to write custom equality test for your instances. And in that case, you should also override the hashCode() method, to maintain the contract of equals() and hashCode().
Finally JDK 8 is going to offer us default methods realization in
interfaces and if which would probably cause multiple inheritance in
Java.
What if interface A provides method a() with default realization and
interface B provides also a() method with another default realization
and our custom class C implements both interfaces and rely on default
realization - wouldn't that be Diamond of Death ?
I can't comment on this concept, because I haven't read about this thing yet. Probably, I would update the answer sometime later.
However how is it possible to inherit from Object and from any other
class at the same time? Isn't that a multiple inheritance.
Unless otherwise specified, a class extends Object. That is, this:
class A { ... }
is equivalent to:
class A extends Object { ... }
Secondly, what for do we need to inherit all 11 Object methods? I
could hardly imagine why do I need it them in I/O e.g.
equals() and hashCode() are used in comparisons and hash tables.
notify() and wait() form the low-level basis of cross-thread communication.
getClass() is the starting point of all reflection code.
By putting them on Object, these can be used on every object in the JVM. You can get the hash code and the class of any object, you can check for equality between any two objects, you can monitor and notify any object.
What if interface A provides method a() with default realization and
interface B provides also a() method with another default realization
and our custom class C implements both interfaces and rely on default
realization - wouldn't that be Diamond of Death ?
As explained in another question here on SO (which is literally just one search for "jdk8 default methods" away):
To solve multiple inheritance issue a class implementing two
interfaces providing a default implementation for the same method name
and signature must provide an implementation of the method.
Thus, the class must provide its own implementation, possibly delegating to one of the default methods.
You are correct about "Diamond of Death" but ...
This is the situation where D implements interfaces C and B and both of those implement A. Further, there is a default method defined in two or more of those interfaces.
In Java 8 they defined a way that the two default method definitions are sorted out.
As I recall, if A and B both have a default method defined, then D uses B's version since it is lower in the class hierarchy.
If B and C both have the same default method defined then there is a conflict and D will need to implement the method itself though it can do so by calling back to the version implemented in either B or C (or it can have conditions and use both in different cases).
interface A { }
interface B implements A { void m() default {println("In A");} }
interface C implements A { void m() default {println("In B");} }
}
class D implements B, C {
public void m() { println("In D"); B.super.m(); }
}
But you can go to Oracle's pages about new features in Java 8 and read all about it. I got there by Googling "Java 8 new features". Found what I was thinking of at http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf
You inherit from a class, which inherits from object. Java does not allow you to inherit from two different class chains. However, the way around this is to use interfaces.
However how is it possible to inherit from Object and from any other
class at the same time?
You cannot do this, you heard wrong.
Secondly, what for do we need to inherit all 11 Object methods? I
could hardly imagine why do I need it them in I/O e.g.
Not sure what you're talking about here.
What if interface A provides method a() with default realization and
interface B provides also a() method with another default realization
and our custom class C implements both interfaces and rely on default
realization - wouldn't that be Diamond of Death ?
Don't know anything about JDK8, but you can already implement a method with the same name/type signature in two interfaces, which is probably illogical but Java allows it.
First- everything is an Object or a primitive in Java so you have no problems here. Object is the class on the top of the hierarchy.
At the moment you can apply multiple interfaces to Java already- then you write your realization. I would imagine that in Java 8- if you define your interface, then you have the realization. If not- then some default is used. If more than one default is defined (or the method is declared by more than one interface)- no default is used. It can be quite simple.

Is a Java interface an abstract class? [duplicate]

This question already has answers here:
implicit super-interface in Java?
(4 answers)
Closed 4 years ago.
I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general?
Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes.
Abstract? Hell yes. Class? No.
Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically it might be true that implementing an interface is actually inheriting it in specific languages, but that's not my point.) Interfaces are more like 'contracts' as they do not define any behaviour whatsoever like classes.
Now if this is a homework then you shouldn't really argue about these sort of stuff with the teacher. Just check your lecture notes and see if the word "class" is mentioned anywhere in the your teacher's definition of interface.
All interface are indeed abstract
Actually, you can declare an method as abstract within an interface... except any 'checkstyle' tool will tell you the abstract keyword is redundant. And all methods are public.
If a class implements an interface and does not implement all its methods, it must be marked as abstract. If a class is abstract, one of its subclasses is expected to implement its unimplemented methods.
To echo other answers, an interface is not a class.
An interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
Interfaces are not part of the class hierarchy, although they work in combination with classes.
When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface
To better explain why an interface is not a class, consider the following:
1/ an interface is a type used by values
2/ a class is for Objects
3/:
Object a = new Date();
String s = a.toString();
The type of the variable 'a' is Object (which is actually a type notation in Java source code meaning a reference to an Object),
but the class of the object it points to is Date.
The type (Object) only affects what code is valid according to the compiler's type-checking, but not what the code actually does.
The class of the object affects what the code does, so that the a.toString() call in the second line returns a String that looks like a Date, not one that looks like "java.lang.Object#XXXXXXXX".
Since an Interface is a type, it is used for values only, and will not represent what objects will actually do in term of runtime.
In Java though, theres a twist to the tale - all Interfaces in Java extend java.lang.Object! Try adding a method:
public void notify();
in an interface and see what happens..
An Interface extending a Class - Does that make the Interface a Class? Or the Class an Interface?? Uhh-huh.. Guess it was a hack that had to be done to prevent interfaces overriding the definitions in java.lang.Object that implementations of the interface had to extend anyway.
You've only asked about the abstract side, but don't forget the class side - I wouldn't call an interface a class, so even though interfaces are abstract (as per the specification), I still don't think they count as abstract classes. It may be worth explicitly explaining that though :)
Yes, an Interface is implicitly Abstract. Look behind the scenes as to the way it is encoded to a .class file.
Semantics are a funny thing though; under exam conditions "abstract class" would have to literally be compiled from a .java source file using abstract class in the Class' declaration.
An interface contains prototype of methods (i.e Declaration ) not defination but Abstract class can contain defination of method & atleast one Abstract method (method with only prototype)
Interfaces are used to break the Object Inheritance.
They could hold two or more objects of several classes
and classes hierarchies.
Look at an interface as an outlet plug. All classes
implementing an Interface need to have one, the same
way a computer, a coffee machine, a ventilator and a
refrigerator need to have the same device to get
power.
Abstract class looks like interface. Abstract classes can have implementations where as interface can't have any implementations.
Then, there is a question. Can we call abstract class as interface if they only have method signatures?
I think, abstract classes, unlike interfaces, are classes. They are expensive to use because there is a lookup to do when you inherit a class from abstract class.

Categories

Resources