I have some confusion on what class name to use from the documentation.
If I want to use the method getLength(Object name) from the Array class the compiler accepts java.lang.reflect.Array.getLength(nameOfArray) but not java.lang.Object.getLength(nameOfArray). Though the picture of the API documentation linked below seems to imply to me that both classes are linked to the Array classes method.
Java API documentation example
The reason you see them linked is that Object is a Superclass of Array.
In Java, Object is the superclass of all classes.
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.
More over here: https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
Each such child class (Array class in this case) inherits some methods from the superclass (Object class in this case).
If the child class wishes to change any of these variables or methods that it inherits from the superclass, then it will override those. In addition, the child class itself may have its own variables and methods which have got nothing to do with the superclass. That is the case in the example you've shown i.e. Array is a data-structure that has a length, but its parent Object does not have a length.
Note: Please read about Inheritance in Java.
In addition, also read about access specifiers (because private members are not inherited), keywords (eg. final variables can't change value, final methods cannot be overriden, final classes can't be subclassed). Good luck!
If I want to use the method getLength(Object name) from the Array class the compiler accepts java.lang.reflect.Array.getLength(nameOfArray)
Correct, because that's where the method is.
but not java.lang.Object.getLength(nameOfArray).
Incorrect, because there is no such method in the java.lang.Object class.
Though the API documentation linked below seems to imply to me that both class paths are linked to the Array classes method.
No it doesn't. The meaning of the part in your picture is that the second class extends the first class.
That documentation example shows that Array is a child of Object, not that you can use them interchangably.
Array extends Object. It means that Any method available for object is available for an Array, but the inverse is not true.
Consider this example. replace Array with Student and Object with Human. Student extends Human. Lets say that Human has getDateOfBirth method. Student also has getGrades method. On Student you can call getDateOfBirth and getGrades, while on Human you can only call getDateOfBirth because grades are not defined for babies.
Note that Object is the superclass of all other classes. As a result it has least number of methods.
Related
All beginners like myself, always get confused to see a method returns an object of an interface type, because interfaces have abstract methods, thus cannot be instantiated.
I finally figured out a way to understand this:
((when we say that a method returns an object of an interface type, we are actually implicitly saying that the method in fact returns an object/instance of some class that implements that interface, but in most cases that class is unknown because it is declared as anonymous in the implementation of the method. Thus, we refer to the returned object as being of that interface type.)).
Is this explanation correct ?
"...when we say that a method returns an object of an interface type, we are actually implicitly saying that the method in fact returns an object/instance of some class that implements that interface..." - It is correct, but we are saying it explicitly.
The second part of your definition is quite not correct, as #Jon Skeet pointed out. Applying anonymous class in the implementation is a very specific case. Generally, returning an interface gives you more freedom:
It is possible to change implementation of the method to return another object that implements the same interface, without changing code that uses this method.
You leave possibility for extending classes to override the method, so that it returns another object that implements the same interface. Here you can actually change the return type. If method of the base class returned concrete class, e.g., ArrayList, overridden method would have to also return ArrayList or its subclass.
The rule of thumb is the following. If concrete class implements an interface and there is no benefit in returning a concrete class object, e.g., ArrayList, return an interface - List, Collection. This will enhance maintainability of your code, i.e., the code will be easier to change in future.
It's my birthday at the end of this month, so I've added a new method to all my friends and family:
public Present givePresent{
//code to select an appropriate and sufficiently expensive present
return present;
}
There's two things I could do here. I could write a Present class and ensure that all possible presents extend it. But we could run in to all sorts of problems here: BatmanComic already inherits from ComicBook for example, so we'd have to move further and further up the tree until Present is basically indistinguishable from Object. The other way is to look at what is actually happening here. I'm looking to receive something that fits in to a specific category and, in short, Java has two ways of doing that. Inheritance and Interfaces. Creating Present as an interface is achieving exactly the same goal as creating it as an abstract superclass but avoids all problems of multiple inheritance. This way all I have to do is write an interface:
public interface Present{
}
and make sure all the socks and books and whatever implement that.
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.
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.
According to the Java API for the Math class, Math extends the Object class:
public final class Math extends Object
However, Math does not inherit Object's methods, and you also cannot construct a Math object (EDIT: this statement is false and partly false; see below).
My question is then why is this done? If it is an object, then it should have the bare-bones methods from Object. If it is not an object, then I feel like it should not be extending Object.
And, assuming there is a good reason for extending Object, how is it done? In other words, how are the inherited methods and constructor suppressed?
Math is the foremost example in my mind of this kind of static definition class (I guess you'd call it that?), but this question may also apply to classes that have a similar purpose.
EDIT: So I'm aware that all classes implicitly extend Object. What's bothering me is that to me there's a logical disconnect between the notion of an "object" in theory-- something with a state and associated functionality-- and what's being done here.
Object is the super class of everything. All classes extend Object
Math does inherit Object's methods. Every class in Java ultimately has to inherit from Object. But since you can't construct Math objects, it doesn't matter. The methods are inherited, but without being able to construct an instance you can't ever use them from Math.
Every class implicitly extends Object unless they extend another class (Java doesn't allow multiple inheritance).
Still! by extending another class you're, in the very end, extending Object, because the last class that doesn't extend another particular class extends Object.
The concept behind this "default inheritance" can be extracted directly from Object's 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: Math does inherit Object's methods. It does not override them tough and the calls are derived to the implementations of the superclass.
You should pay attention to an important aspect of the Math class. The constants and methods it defines are mainly static. Mathematical functions do not depend of a particular instance of the class because those calculations are independent of the context.
You have no particular reason to create an instance of the Math class and that's why its constructor is not visible. You cannot do Math m = new Math() and that's why you don't see methods such as equals or hashcode. In particular since the class is final and can't be extended, you cannot create a sublclass that defines them. IMHO it would be pointless.
Object is the super class of every java class. An you are mistaken that Math does inherit object's methods.
If you want more see the source.
http://www.docjar.com/html/api/java/lang/Math.java.html
The Java documentation for Class says:
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.
What are these Class objects? Are they the same as objects instantiated from a class by calling new?
Also, for example object.getClass().getName() how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?
Nothing gets typecasted to Class. Every Object in Java belongs to a certain class. That's why the Object class, which is inherited by all other classes, defines the getClass() method.
getClass(), or the class-literal - Foo.class return a Class object, which contains some metadata about the class:
name
package
methods
fields
constructors
annotations
and some useful methods like casting and various checks (isAbstract(), isPrimitive(), etc). the javadoc shows exactly what information you can obtain about a class.
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the #Processable annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
Note also that Class object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
To summarize - each object in java has (belongs to) a class, and has a respective Class object, which contains metadata about it, that is accessible at runtime.
A Class object is sort of a meta object describing the class of an object. It is used mostly with the reflection capabilities of Java. You can think of it like a "blueprint" of the actual class. E.g. you have a class Car like this:
public class Car {
public String brand;
}
You can then construct a Class object which describes your "Car" class.
Class myCarClass = Class.forName("Car");
Now you can do all sorts of querying on your Car class on that Class object:
myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field
and so on. Every java object has a method getClass() which returns the Class object describing the Class of the Java object. So you could do something like:
Car myCar = new Car();
Class myCarClass = myCar.getClass();
This also works for objects you don't know, e.g objects you get from the outside:
public void tellMeWhatThisObjectsClassIs(Object obj) {
System.out.println(obj.getClass().getName());
}
You could feed this method any java object and it will print the actual class of the object you have given to it.
When working with Java, most of the time you don't need to worry about Class objects. They have some handy use cases though. E.g. they allow you to programmatically instanciate objects of a certain class, which is used often for object serialization and deserialization (e.g. converting Java Objects back and forth to/from XML or JSON).
Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance(); // is roughly equivalent to = new Car();
You could also use it to find out all declared fields or methods of your class etc, which is very useful in certain cases. So e.g. if your method gets handed an unknown object and you need to know more about it, like if it imlements some interface etc, the Class class is your friend here.
So long story short, the Class, Field, Method, etc. classes which are in the java.lang.reflect package allow you to analyze your defined classes, methods, fields, create new instances of them, call methods all kinds of other stuff and they allow you to do this dynamically at runtime.
getClass() is a method that returns an object that is an instance of java.lang.Class... there is no casting involved. Casting would look like this:
Class<?> type = (Class<?>) object;
I would also like to add to ColinD 's answer that getClass will return the same object for instances of same type. This will print true:
MyOtherClass foo = new MyOtherClass();
MyOtherClass bar = new MyOtherClass();
System.out.println(foo.getClass()==bar.getClass());
Note that it is not equals, I am using ==.
In order to fully understand the class object, let go back in and understand we get the class object in the first place. You see, every .java file you create, when you compile that .java file, the jvm will creates a .class file, this file contains all the information about the class, namely:
Fully qualified name of the class
Parent of class
Method information
Variable fields
Constructor
Modifier information
Constant pool
The list you see above is what you typically see in a typical class. Now, up to this point, your .java file and .class file exists on your hard-disk, when you actually need to use the class i.e. executing code in main() method, the jvm will use that .class file in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .class file into the method area, the jvm will use that information and a Class object that represents that class that exists in the heap memory area.
Here is the top level view,
.java --compile--> .class -->when you execute your script--> .class loads into method area --jvm creates class object from method area--> a class object is born
With a class object, you are obtain information such as class name, and method names, everything about the class.
Also to keep in mind, there shall only be one class object for every class you use in the script.
Hope this makes sense
A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question
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.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method