0

Upcasting& downcasting

https://code.sololearn.com/cRr3Tw4k2riq/?ref=app Could anyone clear my doubt..

21st Aug 2020, 5:10 AM
Haritha Vuppula
Haritha Vuppula - avatar
4 ответов
+ 1
//what methods and variables does superclass and subclass access in upcasting Upcasting is implicit,automatic , which is dame as inheritance, but difference is using parent class refference varisble. It does not change original object. So all variables,methods access are same as inheriting and accessing in subclass. //what methods and methods does superclass and subclass access downcasting access if it successfully,then all methods of subclass, super class methods which are not overridden.. //what is purpose of these upcasting downcasting? Usefull for making object to target type of object from more general type of object to specific type of object. Grnerics are best examples.. class superclass { } class childclass1 extends superclass { } class childclass2 extends superclass { } class demo { public static void main(String[] args){ superclass s= new superclass();//normal childclass c = new childclass();//normal superclass upc = new childclass();//upcasting System.out.println(upc.a); //this can be cal
21st Aug 2020, 3:50 PM
Jayakrishna 🇮🇳
+ 1
Ctd: superclass upc = new childclass();//upcasting System.out.println(upc.a); //this can be called through 's' why upcasting? Yes. But in that case you cannot call subclass objects by s object. But by after cast you can do that now, with one object only.; otherwise you have 2 object in object pool with redundant code references. childclass dc = (childclass)upc;//downcasting System.out.println(dc.sing());/*this can be called through line 46,means through'c' so y downcasting*/ Yes. But you declared child class object when you have already a refference variable, which you can use.. See i modfied code that if you have another subclass childclass2, then you can refference through c object for childclass2 methods, you need casting like childclass2 dc2=(childclass2)upc; Like this we can have many classes.. Not only single one. } It is in my opinion, there i may missing some points... Lets discuss with others, if I miss or wrong anything... https://javarevisited.blogspot.com/2012/12/what-is-type-casting-in-java-c
21st Aug 2020, 3:52 PM
Jayakrishna 🇮🇳
21st Aug 2020, 4:13 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
Haritha Vuppula You're welcome.. Edit: For clear info, read this link below, about example ArrayList.. ArrayList l = new ArrayList(); In to this list, you can add any type data.. But if you only integers, then you need down casting to ArrayList<Integer> l = new ArrayList() ; https://javarevisited.blogspot.com/2012/12/what-is-type-casting-in-java-class-interface-example.html?m=1 Also may this helps.. https://medium.com/@shivachetan0/upcasting-and-downcasting-in-java-f454f173e1ef
21st Aug 2020, 4:14 PM
Jayakrishna 🇮🇳