Comparing two classes by its types or class names

前端 未结 7 1098
耶瑟儿~
耶瑟儿~ 2021-02-01 15:34

There is need to compare two objects based on class they implement? When to compare using getClass() and when getClass().getName()? Is there any differ

相关标签:
7条回答
  • 2021-02-01 16:03

    Another way to achieve the same will be by overriding hashcode in subclass.

    public interface Parent {
    }
    
    public static class Child1 implements Parent{
        private String anyfield="child1";
    
        @Override
        public int hashCode() {
            //Code based on "anyfield"
        }
    
        @Override
        public boolean equals(Object obj) {
            //equals based on "anyfield"
        }
    }
    
    public static class Child2 implements Parent{
        private String anyfield="child2";
    
        @Override
        public int hashCode() {
            //Code based on "anyfield"
        }
    
        @Override
        public boolean equals(Object obj) {
            //equals based on "anyfield"
        }
    }
    

    Now the equals will return if implementations/subclasses are of same concrete type.

    public static void main(String args[]){
        Parent p1=new Child1();
        Parent p2=new Child1();
        Parent p3=new Child2();
        System.out.println("p1 and p2 are same : "+p1.equals(p2));
        System.out.println("p2 and p3 are same : "+p2.equals(p3));
    }
    

    Output-

    p1 and p2 are same : true
    p2 and p3 are same : false
    
    0 讨论(0)
提交回复
热议问题