Comparing Class Types in Java

前端 未结 8 2032
不知归路
不知归路 2020-12-14 06:07

I want to compare the class type in Java.

I thought I could do this:

class MyObject_1 {}
class MyObject_2 extends MyObject_1 {}

public boolean funct         


        
8条回答
  •  攒了一身酷
    2020-12-14 06:12

    If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object.

    This is because they are both references on the same class object. This is true for all classes in a java application. Java only loads the class once, so you have only one instance of a given class at a given time.

    String hello  = "Hello";
    String world = "world";
    
    if (hello.getClass() == world.getClass()) {
        System.out.println("true");
    } // prints true
    

提交回复
热议问题