简体   繁体   中英

how to know the type of reference referring to a object in java?

 package example;
    class Machine
    {
        public void start()
       {
            System.out.println("MACHINE IS STARTING");
       }
    }
    class Camera extends Machine
    {
        public void snap()
        {
            System.out.println("SNAP");
        }
    }

    public class App {
        public static void main(String args[])
        {
            Camera cam1 = new Camera();
            Machine mach1 = cam1; 

        }

    }

in the above code camera object is being refereed by both cam1 which is of type Camera and mach1 of type Machine . Is there any function which can tell the type of references that are being referred to that object???

If you want to know the class of the instance referenced by the mach1 variable, use :

mach1.getClass().getName()

If you want to test if mach1 is of a specific type, use instanceof

if (mach1 instanceof Camera)

You can use the getclass method for it

java.lang.Object.getClass()

mach1.getClass().getName()

it will return the runtime class of an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM