Flexible nature of java.lang.Object

Course Curriculum

Flexible nature of java.lang.Object

Flexible nature of java.lang.Object

We all love the mechanism of python, where we don’t have to bother about data types of the variables (don’t we!)

Interestingly we have one class in Java too, which is pretty similar !

Yes, you guessed it right! It’s java.lang.Object

For example,

// A Java program to demonstrate flexible nature of
// java.lang.Object
public class Prutor
{
public static void main(String arr[])
{
Object y;

y = 'A';
System.out.println(y.getClass().getName());

y = 1;
System.out.println(y.getClass().getName());

y = "Hi";
System.out.println(y.getClass().getName());

y = 1.222;
System.out.println(y.getClass().getName());

y = false;
System.out.println(y.getClass().getName());
}
}
Output:

java.lang.Character
java.lang.Integer
java.lang.String
java.lang.Double
java.lang.Boolean
Such a behaviour can be attributed to the fact that java.lang.Object is super class to all other classes. Hence, a reference variable of type Object can be practically used to refer objects of any class. So, we could also assign y = new InputStreamReader(System.in) in the above code!

Static class in Java (Prev Lesson)
(Next Lesson) Overriding equals method in Java
', { 'anonymize_ip': true });