Upcasting and Downcasting in java

后端 未结 8 1619
孤城傲影
孤城傲影 2021-01-13 21:26

I can understand what upcasting is but Downcasting is a little confusing. My question is why should we downcast? Can you help me with a real time example ? Is downcasting th

相关标签:
8条回答
  • 2021-01-13 22:07

    With the introduction of generics, it is less important than it was before, but there are times when you need it.

    For instance, when you read an object from an ObjectInputStream.

    0 讨论(0)
  • 2021-01-13 22:07

    One place you need it is if you override the equals method inherited from Object. Since the parameter passed to the method is of type Object, you have to cast it to the type of the class to be able to access methods and variables defined in it. Just pay special attention to what referred to object is. That is to say, instantiated object is passed to the equals() method, not its reference.

    class MySuperClass
    {
        private int num1;
    
        public MySuperClass() {}
    
        public MySuperClass(int num1)
        {
            this.num1 = num1;
        }
    }
    
    class MySubClass extends MySuperClass
    {
        private int num;
    
        public MySubClass(int num)
        {
            this.num = num;
        }
    
        public boolean equals(Object o)
        {
            if (!(o instanceof MySubClass))
                return false;
    
            MySubClass mySub = (MySubClass)o;
    
            return(mySub.num == num);
        }
    
        public static void main(String[] args)
        {
            Object mySub = new MySubClass(1);
            MySuperClass mySup = new MySubClass(1);
    
            System.out.println(mySub.equals(mySup));
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题