Open In App
Related Articles

Flexible nature of java.lang.Object

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

We all love the mechanism of python, where we don’t have to bother about the data types of the variables. Interestingly we have one class in Java too, which is pretty similar! It’s java.lang.Object.

Example:

Java

// Java program to Demonstrate Flexible Nature of
// java.lang.Object
 
// Importing required classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String arr[])
    {
 
        // Declaring a variable of Object class type
        Object y;
 
        y = 'A';
 
        // Getting the class name
        // using getClass() and getname() method
        System.out.println(y.getClass().getName());
 
        y = 1;
       
        // Getting the class name
        System.out.println(y.getClass().getName());
 
        y = "Hi";
       
        // Getting the class name
        System.out.println(y.getClass().getName());
 
        y = 1.222;
       
        // Getting the class name
        System.out.println(y.getClass().getName());
 
        y = false;
       
        // Getting the class name
        System.out.println(y.getClass().getName());
    }
}

                    

Output
java.lang.Character
java.lang.Integer
java.lang.String
java.lang.Double
java.lang.Boolean

Such behavior can be attributed to the fact that the Object class is a superclass to all other classes. Hence, a reference variable of type Object can be practically used to reference objects of any class. So, we could also assign y = new InputStreamReader(System.in) in the above code.



Last Updated : 02 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads