{"id":14773,"date":"2023-03-22T10:27:07","date_gmt":"2023-03-22T10:27:07","guid":{"rendered":"https:\/\/www.prepbytes.com\/blog\/?p=14773"},"modified":"2023-12-27T07:13:21","modified_gmt":"2023-12-27T07:13:21","slug":"upcasting-and-downcasting-in-java","status":"publish","type":"post","link":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/","title":{"rendered":"Upcasting and Downcasting in Java"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg\" alt=\"\" \/><\/p>\n<p>In Java, casting refers to the conversion of one data type to another. Upcasting and downcasting specifically relate to the casting of objects in the context of class hierarchies, commonly associated with inheritance. Upcasting involves converting a reference of a subclass to a reference of its superclass, while downcasting involves converting a reference of a superclass to a reference of its subclass. Understanding and using these concepts are essential for working with polymorphism and leveraging the full potential of object-oriented programming in Java.<br \/>\nUpcasting is inherently safe, as it involves moving from a more specific type to a more general type. On the other hand, downcasting carries some risk, and developers need to ensure that the object being cast is indeed an instance of the subclass to avoid runtime errors.<\/p>\n<h2>Typecasting in Java<\/h2>\n<p>The process of converting one data type into another is known as typecasting in java. It is one of the most important concepts of java. As it deals with the conversion of one data type into another data type explicitly or implicitly.<br \/>\nLike the data type, we can also typecast the objects.<br \/>\nYou can refer to <a href=\"https:\/\/prepbytes.com\/blog\/java\/type-casting-in-java\/#:~:text=Introduction%20to%20Type%20Casting%20in%20Java&amp;amp;text=The%20concept%20of%20Type%20Casting,is%20known%20as%20type%20casting.\" title=\"Typecasting in Java\">Typecasting in Java<\/a> for further knowledge on typecasting.<\/p>\n<p>There are two types of object typecasting available in java and they are mentioned below:<\/p>\n<ul>\n<li>Upcasting<\/li>\n<li>Downcasting<\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022151-1-01%20%2815%29.png\" alt=\"\" \/><\/p>\n<h2>Upcasting in Java<\/h2>\n<p>In simple words upcasting in java is a type of object typecasting where we are typecasting a child object to a parent object. The upcasting is done implicitly there is no need to explicitly refer to the parent class. The upcasting gives us the benefit of accessing all the methods and variables of the parent class. But in upcasting we cannot access all the variables and methods of the child class. We can only access some specified methods and variables of the child class. Upcasting can also be referred to as Widening and Generalization.<\/p>\n<p><strong>Syntax of Upcasting in Java<\/strong><br \/>\nThe syntax of upcasting in java is given below:<\/p>\n<pre><code>Parent p= new Child();<\/code><\/pre>\n<p><strong>Example of Upcasting in Java<\/strong><br \/>\nBelow is the example of upcasting.<\/p>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_14732 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_14732 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_14732 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_14732 .wpsm_nav-tabs > li.active > a, #tab_container_14732 .wpsm_nav-tabs > li.active > a:hover, #tab_container_14732 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_14732 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_14732 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_14732 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_14732 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_14732 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_14732 .wpsm_nav-tabs > li > a:hover , #tab_container_14732 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_14732 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_14732 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_14732 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_14732 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_14732 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_14732 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_14732 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_14732 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_14732 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_14732 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_14732 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_14732\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_14732\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_14732_1\" aria-controls=\"tabs_desc_14732_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_14732\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_14732_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">class Vehicle{\r\n    void drive(){\r\n        System.out.println(\"Driving a vehicle...\");\r\n    }\r\n}\r\nclass Car extends Vehicle{\r\n    void drive(){\r\n        System.out.println(\"Driving a car...\");\r\n    }\r\n    void speedUp(){\r\n        System.out.println(\"Speeding up a car...\");\r\n    }\r\n}\r\nclass Main{\r\n    public static void main(String[] args){\r\n        Vehicle v = new Car();\r\n        v.drive();\r\n    }\r\n}\r\n\r\n<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_14732 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_14732 a\"),jQuery(\"#tab-content_14732\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<p><strong>Output<\/strong><\/p>\n<pre><code>Driving a car\u2026 when a reference variable of a superclass is assigned to a reference variable of<\/code><\/pre>\n<p><strong>Explanation of the above example<\/strong><br \/>\nIn the above example we have a parent class Vehicle and a child class with the name Car. The Car class extends the Vehicle class and overrides the drive() method. In the main() class we have created an object of the car class and then assign it to the reference variable of the vehicle class.<br \/>\nEven though we have assigned a Car object to a Vehicle reference variable, the drive() method of the Car class is invoked because the Car class overrides the drive() method of the Vehicle class.<\/p>\n<h2>Downcasting in Java<\/h2>\n<p>Another form of object typecasting is downcasting. A parent class reference object is given to the child class during downcasting. Although it is not possible to give a parent class reference object to a child class in Java, if downcasting is used, there won&#8217;t be any compile-time errors. The &quot;ClassCastException&quot; is thrown when we attempt to execute it. The question is, why is downcasting permitted by the compiler if it is not feasible in Java? In some Java situations, downcasting is an option. The master class in this case refers to the subclass object.<\/p>\n<p><strong>Syntax of Downcasting in Java<\/strong><br \/>\nThe syntax of downcasting in java is given below:<\/p>\n<pre><code>Child c= (Child) p;<\/code><\/pre>\n<p><strong>Example of Downcasting in Java<\/strong><br \/>\nBelow is the example of downsampling in java with code implementation.<\/p>\n\t\t\t\t\t\t<style>\r\n\t\t\t\t\r\n\t\t\t\t\t#tab_container_14734 {\r\n\toverflow:hidden;\r\n\tdisplay:block;\r\n\twidth:100%;\r\n\tborder:0px solid #ddd;\r\n\tmargin-bottom:30px;\r\n\t}\r\n\r\n#tab_container_14734 .tab-content{\r\n\tpadding:20px;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n\tmargin-top: 0px;\r\n\tbackground-color:#ffffff !important;\r\n\tcolor: #000000 !important;\r\n\tfont-size:16px !important;\r\n\tfont-family: Open Sans !important;\r\n\t\r\n\t\tborder: 1px solid #e6e6e6 !important;\r\n\t}\r\n#tab_container_14734 .wpsm_nav-tabs {\r\n    border-bottom: 0px solid #ddd;\r\n}\r\n#tab_container_14734 .wpsm_nav-tabs > li.active > a, #tab_container_14734 .wpsm_nav-tabs > li.active > a:hover, #tab_container_14734 .wpsm_nav-tabs > li.active > a:focus {\r\n\tcolor: #000000 !important;\r\n\tcursor: default;\r\n\tbackground-color: #ffffff !important;\r\n\tborder: 1px solid #e6e6e6 !important;\r\n}\r\n\r\n#tab_container_14734 .wpsm_nav-tabs > li > a {\r\n    margin-right: 0px !important; \r\n    line-height: 1.42857143 !important;\r\n    border: 1px solid #d5d5d5 !important;\r\n    border-radius: 0px 0px 0 0 !important; \r\n\tbackground-color: #e8e8e8 !important;\r\n\tcolor: #000000 !important;\r\n\tpadding: 15px 18px 15px 18px !important;\r\n\ttext-decoration: none !important;\r\n\tfont-size: 14px !important;\r\n\ttext-align:center !important;\r\n\tfont-family: Open Sans !important;\r\n}\r\n#tab_container_14734 .wpsm_nav-tabs > li > a:focus {\r\noutline: 0px !important;\r\n}\r\n\r\n#tab_container_14734 .wpsm_nav-tabs > li > a:before {\r\n\tdisplay:none !important;\r\n}\r\n#tab_container_14734 .wpsm_nav-tabs > li > a:after {\r\n\tdisplay:none !important ;\r\n}\r\n#tab_container_14734 .wpsm_nav-tabs > li{\r\npadding:0px !important ;\r\nmargin:0px;\r\n}\r\n\r\n#tab_container_14734 .wpsm_nav-tabs > li > a:hover , #tab_container_14734 .wpsm_nav-tabs > li > a:focus {\r\n    color: #000000 !important;\r\n    background-color: #e8e8e8 !important;\r\n\tborder: 1px solid #d5d5d5 !important;\r\n\t\r\n}\r\n#tab_container_14734 .wpsm_nav-tabs > li > a .fa{\r\n\r\nmargin-right:5px !important;\r\n\r\nmargin-left:5px !important;\r\n\r\n\r\n}\r\n\r\n\t\t#tab_container_14734 .wpsm_nav-tabs a{\r\n\t\t\tbackground-image: none;\r\n\t\t\tbackground-position: 0 0;\r\n\t\t\tbackground-repeat: repeat-x;\r\n\t\t}\r\n\t\t\t\r\n\r\n\r\n#tab_container_14734 .wpsm_nav-tabs > li {\r\n    float: left;\r\n    margin-bottom: -1px !important;\r\n\tmargin-right:0px !important; \r\n}\r\n\r\n\r\n#tab_container_14734 .tab-content{\r\noverflow:hidden !important;\r\n}\r\n\r\n\r\n@media (min-width: 769px) {\r\n\r\n\t#tab_container_14734 .wpsm_nav-tabs > li{\r\n\t\tfloat:left !important ;\r\n\t\t\t\tmargin-right:-1px !important;\r\n\t\t\t\t\t}\r\n\t#tab_container_14734 .wpsm_nav-tabs{\r\n\t\tfloat:none !important;\r\n\t\tmargin:0px !important;\r\n\t}\r\n\r\n\t#tab_container_14734 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_14734 .wpsm_nav{\r\n\t\t\t}\r\n\r\n}\r\n\r\n\r\n\r\n@media (max-width: 768px) {\r\n\t#tab_container_14734 .wpsm_nav-tabs > li {\r\n\t\t\t\t\r\n\t}\r\n\t#tab_container_14734 .wpsm_nav{\r\n\t\t\t}\r\n}\r\n\r\n\r\n\t.wpsm_nav-tabs li:before{\r\n\t\tdisplay:none !important;\r\n\t}\r\n\r\n\t@media (max-width: 768px) {\r\n\t\t\t\t\r\n\t\t\t\t.wpsm_nav-tabs{\r\n\t\t\tmargin-left:0px !important;\r\n\t\t\tmargin-right:0px !important; \r\n\t\t\t\r\n\t\t}\r\n\t\t\t\t#tab_container_14734 .wpsm_nav-tabs > li{\r\n\t\t\tfloat:none !important;\r\n\t\t}\r\n\t\t\t\r\n\t}\t\t\t\t<\/style>\r\n\t\t\t\t<div id=\"tab_container_14734\" >\r\n\t \r\n\t\t\t\t\t<ul class=\"wpsm_nav wpsm_nav-tabs\" role=\"tablist\" id=\"myTab_14734\">\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t<li role=\"presentation\"  class=\"active\"  onclick=\"do_resize()\">\r\n\t\t\t\t\t\t\t\t<a href=\"#tabs_desc_14734_1\" aria-controls=\"tabs_desc_14734_1\" role=\"tab\" data-toggle=\"tab\">\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<i class=\"fa fa-code\"><\/i> \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t<span>Java<\/span>\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t<\/a>\r\n\t\t\t\t\t\t\t<\/li>\r\n\t\t\t\t\t\t\t\t\t\t\t <\/ul>\r\n\r\n\t\t\t\t\t  <!-- Tab panes -->\r\n\t\t\t\t\t  <div class=\"tab-content\" id=\"tab-content_14734\">\r\n\t\t\t\t\t\t\t\t\t\t\t\t <div role=\"tabpanel\" class=\"tab-pane  in active \" id=\"tabs_desc_14734_1\">\r\n\t\t\t\t\t\t\t\t<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">class Vehicle{\r\n    void drive(){\r\n        System.out.println(\"Driving a vehicle...\");\r\n    }\r\n}\r\nclass Car extends Vehicle{\r\n    void drive(){\r\n        System.out.println(\"Driving a car...\");\r\n    }\r\n    void speedUp(){\r\n        System.out.println(\"Speeding up a car...\");\r\n    }\r\n}\r\nclass Main{\r\n    public static void main(String[] args){\r\n        Vehicle v = new Car();\r\n        Car c = (Car) v;\r\n        c.drive();\r\n        c.speedUp();\r\n    }\r\n}\r\n<\/pre>\t\t\t\t\t\t <\/div>\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t <\/div>\r\n\t\t\t\t\t \r\n\t\t\t\t <\/div>\r\n <script>\r\n\t\tjQuery(function () {\r\n\t\t\tjQuery('#myTab_14734 a:first').tab('show')\r\n\t\t});\r\n\t\t\r\n\t\t\t\tjQuery(function(){\r\n\t\t\tvar b=\"fadeIn\";\r\n\t\t\tvar c;\r\n\t\t\tvar a;\r\n\t\t\td(jQuery(\"#myTab_14734 a\"),jQuery(\"#tab-content_14734\"));function d(e,f,g){\r\n\t\t\t\te.click(function(i){\r\n\t\t\t\t\ti.preventDefault();\r\n\t\t\t\t\tjQuery(this).tab(\"show\");\r\n\t\t\t\t\tvar h=jQuery(this).data(\"easein\");\r\n\t\t\t\t\tif(c){c.removeClass(a);}\r\n\t\t\t\t\tif(h){f.find(\"div.active\").addClass(\"animated \"+h);a=h;}\r\n\t\t\t\t\telse{if(g){f.find(\"div.active\").addClass(\"animated \"+g);a=g;}else{f.find(\"div.active\").addClass(\"animated \"+b);a=b;}}c=f.find(\"div.active\");\r\n\t\t\t\t});\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\r\n\t\tfunction do_resize(){\r\n\r\n\t\t\tvar width=jQuery( '.tab-content .tab-pane iframe' ).width();\r\n\t\t\tvar height=jQuery( '.tab-content .tab-pane iframe' ).height();\r\n\r\n\t\t\tvar toggleSize = true;\r\n\t\t\tjQuery('iframe').animate({\r\n\t\t\t    width: toggleSize ? width : 640,\r\n\t\t\t    height: toggleSize ? height : 360\r\n\t\t\t  }, 250);\r\n\r\n\t\t\t  toggleSize = !toggleSize;\r\n\t\t}\r\n\r\n\r\n\t<\/script>\r\n\t\t\t\t\r\n\t\t\t\n<p><strong>Output<\/strong><\/p>\n<pre><code>Driving a car...\nSpeeding up a car...<\/code><\/pre>\n<p><strong>Explanation of the above example<\/strong><br \/>\nIn the above example we have a parent-class vehicle and a child-class car. The car extends to the reference of the parent class and overrides the drive method. It also has a new method known as speedup. We have created an object of type car in the main function then downcast it. In the above program, we upcast a Car object to a Vehicle reference variable and then downcast it back to a Car reference variable. This allows us to call the methods of the Car class.<\/p>\n<h2>Why do we use Upcasting and Downcasting in Java?<\/h2>\n<p>We do not use upcasting too often in java, We use upcasting in java only when the code needs to deal with only the parent class not much with the child class. Whereas we use downcasting when we need to access all the methods of child classes.<\/p>\n<h2>Difference between Upcasting and Downcasting<\/h2>\n<p>Here are some of the differences between Upcasting and Downcasting.<\/p>\n<table>\n<thead>\n<tr>\n<th>Basis<\/th>\n<th>Upcasting<\/th>\n<th>Downcasting<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Direction<\/td>\n<td>It always goes from subclass to superclass.<\/td>\n<td>It goes from superclass to subclass.<\/td>\n<\/tr>\n<tr>\n<td>Safety<\/td>\n<td>It is comparatively safe as it does not require checks on runtime.<\/td>\n<td>We need to perform regular checks on runtime.<\/td>\n<\/tr>\n<tr>\n<td>Access<\/td>\n<td>In the child class we can only access the methods of the parent class.<\/td>\n<td>We can access the methods of both child and parent classes.<\/td>\n<\/tr>\n<tr>\n<td>Method<\/td>\n<td>We can perform this implicitly or explicitly.<\/td>\n<td>We can perform this only explicitly.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p><strong>Conclusion<\/strong><br \/>\nIn conclusion, upcasting and downcasting in Java are integral aspects of object-oriented programming that facilitate the manipulation of objects in class hierarchies. Upcasting allows for the flexibility of treating subclasses as instances of their superclass, enabling polymorphic behavior. Downcasting, while powerful, requires careful validation to avoid runtime exceptions and is typically used when specific methods or attributes of a subclass are needed.<br \/>\nThese casting mechanisms contribute to the dynamic and adaptable nature of Java&#8217;s object-oriented model, allowing developers to write more generic and reusable code while still taking advantage of the specific features of subclasses.<\/p>\n<h2>Frequently Asked Questions Related to Upcasting and Downcasting in Java<\/h2>\n<p>Below are some frequently asked questions and answers about upcasting and downcasting in java.<\/p>\n<p><strong>1. When is downcasting necessary in Java?<\/strong><br \/>\nDowncasting is necessary when you need to access methods or attributes specific to a subclass that are not present in the superclass. It is often required to utilize the full functionality of an object within a class hierarchy.<\/p>\n<p><strong>2. What happens if I attempt to downcast without checking the type using instanceof?<\/strong><br \/>\nIf downcasting is attempted without validating the type using instanceof, it may result in a ClassCastException at runtime. This exception occurs when the object being cast is not an instance of the specified subclass.<\/p>\n<p><strong>3. Can interfaces be upcast and downcast in a similar manner as classes?<\/strong><br \/>\nYes, interfaces can also be upcast and downcast in Java. An interface reference can be upcast to a reference of its superinterface, and downcasting is performed similarly with the use of the instanceof operator.<\/p>\n<p><strong>4. Are upcasting and downcasting limited to class hierarchies, or do they apply to interfaces as well?<\/strong><br \/>\nBoth upcasting and downcasting apply not only to class hierarchies but also to interfaces. The principles remain the same, allowing for flexibility and polymorphism in the context of both classes and interfaces.<\/p>\n<p><strong>5. Can downcasting be performed on null references?<\/strong><br \/>\nAttempting to downcast a null reference will result in a NullPointerException. It is essential to ensure that the object being downcast is not null before attempting the operation to avoid runtime errors.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Java, casting refers to the conversion of one data type to another. Upcasting and downcasting specifically relate to the casting of objects in the context of class hierarchies, commonly associated with inheritance. Upcasting involves converting a reference of a subclass to a reference of its superclass, while downcasting involves converting a reference of a [&hellip;]<\/p>\n","protected":false},"author":52,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[143],"tags":[],"class_list":["post-14773","post","type-post","status-publish","format-standard","hentry","category-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.8 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Upcasting and Downcasting in Java<\/title>\n<meta name=\"description\" content=\"Learn about upcasting and downcasting in java along with why we use them, examples of both and applications of upcasting and downcasting in java.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Upcasting and Downcasting in Java\" \/>\n<meta property=\"og:description\" content=\"Learn about upcasting and downcasting in java along with why we use them, examples of both and applications of upcasting and downcasting in java.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"PrepBytes Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prepbytes0211\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-22T10:27:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-12-27T07:13:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg\" \/>\n<meta name=\"author\" content=\"Prepbytes\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prepbytes\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\"},\"author\":{\"name\":\"Prepbytes\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\"},\"headline\":\"Upcasting and Downcasting in Java\",\"datePublished\":\"2023-03-22T10:27:07+00:00\",\"dateModified\":\"2023-12-27T07:13:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\"},\"wordCount\":1159,\"commentCount\":0,\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg\",\"articleSection\":[\"Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\",\"url\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\",\"name\":\"Upcasting and Downcasting in Java\",\"isPartOf\":{\"@id\":\"http:\/\/43.205.93.38\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg\",\"datePublished\":\"2023-03-22T10:27:07+00:00\",\"dateModified\":\"2023-12-27T07:13:21+00:00\",\"description\":\"Learn about upcasting and downcasting in java along with why we use them, examples of both and applications of upcasting and downcasting in java.\",\"breadcrumb\":{\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage\",\"url\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg\",\"contentUrl\":\"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"http:\/\/43.205.93.38\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java\",\"item\":\"https:\/\/prepbytes.com\/blog\/category\/java\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Upcasting and Downcasting in Java\"}]},{\"@type\":\"WebSite\",\"@id\":\"http:\/\/43.205.93.38\/#website\",\"url\":\"http:\/\/43.205.93.38\/\",\"name\":\"PrepBytes Blog\",\"description\":\"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING\",\"publisher\":{\"@id\":\"http:\/\/43.205.93.38\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"http:\/\/43.205.93.38\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"http:\/\/43.205.93.38\/#organization\",\"name\":\"Prepbytes\",\"url\":\"http:\/\/43.205.93.38\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"contentUrl\":\"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp\",\"width\":160,\"height\":160,\"caption\":\"Prepbytes\"},\"image\":{\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/prepbytes0211\/\",\"https:\/\/www.instagram.com\/prepbytes\/\",\"https:\/\/www.linkedin.com\/company\/prepbytes\/\",\"https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA\"]},{\"@type\":\"Person\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e\",\"name\":\"Prepbytes\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"http:\/\/43.205.93.38\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g\",\"caption\":\"Prepbytes\"},\"url\":\"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Upcasting and Downcasting in Java","description":"Learn about upcasting and downcasting in java along with why we use them, examples of both and applications of upcasting and downcasting in java.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Upcasting and Downcasting in Java","og_description":"Learn about upcasting and downcasting in java along with why we use them, examples of both and applications of upcasting and downcasting in java.","og_url":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/","og_site_name":"PrepBytes Blog","article_publisher":"https:\/\/www.facebook.com\/prepbytes0211\/","article_published_time":"2023-03-22T10:27:07+00:00","article_modified_time":"2023-12-27T07:13:21+00:00","og_image":[{"url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg","type":"","width":"","height":""}],"author":"Prepbytes","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Prepbytes","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#article","isPartOf":{"@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/"},"author":{"name":"Prepbytes","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e"},"headline":"Upcasting and Downcasting in Java","datePublished":"2023-03-22T10:27:07+00:00","dateModified":"2023-12-27T07:13:21+00:00","mainEntityOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/"},"wordCount":1159,"commentCount":0,"publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg","articleSection":["Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/","url":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/","name":"Upcasting and Downcasting in Java","isPartOf":{"@id":"http:\/\/43.205.93.38\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage"},"image":{"@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg","datePublished":"2023-03-22T10:27:07+00:00","dateModified":"2023-12-27T07:13:21+00:00","description":"Learn about upcasting and downcasting in java along with why we use them, examples of both and applications of upcasting and downcasting in java.","breadcrumb":{"@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#primaryimage","url":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg","contentUrl":"https:\/\/prepbytes-misc-images.s3.ap-south-1.amazonaws.com\/assets\/1679461022051-Upcasting%20and%20Downcasting%20in%20Java.jpg"},{"@type":"BreadcrumbList","@id":"https:\/\/prepbytes.com\/blog\/upcasting-and-downcasting-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"http:\/\/43.205.93.38\/"},{"@type":"ListItem","position":2,"name":"Java","item":"https:\/\/prepbytes.com\/blog\/category\/java\/"},{"@type":"ListItem","position":3,"name":"Upcasting and Downcasting in Java"}]},{"@type":"WebSite","@id":"http:\/\/43.205.93.38\/#website","url":"http:\/\/43.205.93.38\/","name":"PrepBytes Blog","description":"ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING","publisher":{"@id":"http:\/\/43.205.93.38\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"http:\/\/43.205.93.38\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"http:\/\/43.205.93.38\/#organization","name":"Prepbytes","url":"http:\/\/43.205.93.38\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/","url":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","contentUrl":"https:\/\/blog.prepbytes.com\/wp-content\/uploads\/2025\/07\/uzxxllgloialmn9mhwfe.webp","width":160,"height":160,"caption":"Prepbytes"},"image":{"@id":"http:\/\/43.205.93.38\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/prepbytes0211\/","https:\/\/www.instagram.com\/prepbytes\/","https:\/\/www.linkedin.com\/company\/prepbytes\/","https:\/\/www.youtube.com\/channel\/UC0xGnHDrjUM1pDEK2Ka5imA"]},{"@type":"Person","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/3f7dc4ae851791d5947a7f99df363d5e","name":"Prepbytes","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"http:\/\/43.205.93.38\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/232042cd1a1ea0e982c96d2a2ec93fb70a8e864e00784491231e7bfe5a9e06b5?s=96&d=mm&r=g","caption":"Prepbytes"},"url":"https:\/\/prepbytes.com\/blog\/author\/gourav-jaincollegedekho-com\/"}]}},"_links":{"self":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/14773","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/users\/52"}],"replies":[{"embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/comments?post=14773"}],"version-history":[{"count":2,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/14773\/revisions"}],"predecessor-version":[{"id":18584,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/posts\/14773\/revisions\/18584"}],"wp:attachment":[{"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/media?parent=14773"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/categories?post=14773"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prepbytes.com\/blog\/wp-json\/wp\/v2\/tags?post=14773"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}