instanceof Vs getClass( )

后端 未结 4 1843
一向
一向 2020-12-02 04:36

I see gain in performance when using getClass() and == operator over instanceOf operator.

Object  str = new Integer(\"         


        
4条回答
  •  悲哀的现实
    2020-12-02 04:59

    getClass() has the restriction that objects are only equal to other objects of the same class, the same run time type, as illustrated in the output of below code:

    class ParentClass{
    }
    public class SubClass extends ParentClass{
        public static void main(String []args){
            ParentClass parentClassInstance = new ParentClass();
            SubClass subClassInstance = new SubClass();
            if(subClassInstance instanceof ParentClass){
                System.out.println("SubClass extends ParentClass. subClassInstance is instanceof ParentClass");
            }
            if(subClassInstance.getClass() != parentClassInstance.getClass()){
                System.out.println("Different getClass() return results with subClassInstance and parentClassInstance ");
            }
        }
    }
    

    Outputs:

    SubClass extends ParentClass. subClassInstance is instanceof ParentClass.

    Different getClass() return results with subClassInstance and parentClassInstance.

提交回复
热议问题