Upcasting and Downcasting in Java
You must have heard of the programming language, Java if you have even the slightest interest in programming. Its versatility and compatibility have made it a highly valued programming language. Some of the most popular applications and platforms like Google, Android OS, Netflix, Spotify, Amazon, and Minecraft use Java to support their products.
Today, Java is one of the most popular and widely used programming languages in the world which has stood the test of time. Whether you are developing mobile applications, web applications, client-server applications, enterprise applications, or computer games, knowledge of Java is absolutely essential for programmers.
Given how important Java is for programming, you must be itching to explore some of the most important concepts related to it. In this article, we delve into one such aspect: what is upcasting and downcasting in Java.
Before we begin exploring the concepts of upcasting and downcasting in Java, you need to understand the concept of typecasting.
Check out our free courses to get an edge over the competition.
Typecasting in Java refers to the procedure that involves the conversion of one data type to another. This can be done both automatically and manually. While a programmer has to do the manual conversion on their own, a compiler is used for the automatic process. Downcasting and upcasting essentially are two types of object typecasting.
Check out upGrad’s Advanced Certification in Cyber Security
Child and parent objects are two distinctive types of objects. Now, there are two ways with the help of which the objects can be initialized, subsequently also inheriting the properties that the child and parent classes have. These ways include:
- Child c = new Child(): Accesses all members coming under child and parent classes
- Parent p = new Child(): Accesses the parent class members only, as well as the methods that have been overridden in the child class
Essentially, Parent to Child type casting is known as Upcasting, while Child to Parent type casting is referred to as Downcasting.
Check out upGrad’s Advanced Certification in Cloud Computing
The typecasting system is used to see to it that the variables are processed by a function accurately or not. While downcasting is not possible implicitly, one can perform upcasting both explicitly and implicitly.
Both downcasting and upcasting are important elements of Java and enables people to develop complex programs with the usage of simple syntax. They also have some great advantages like grouping diverse objects together or Polymorphism.
Learn Online software development courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
Explore our Popular Software Engineering Courses
Let’s look more closely at what is upcasting in Java.
In upcasting, a child object is a typecast to a parent class object. With the usage of this process, people can avail access to the distinguished methods and variables of the parent to child class with ease. Access to only some of the particular methods and variables of the child class, such as the overridden methods, are required in the process. In many instances, upcasting is also called widening and generalising. Upcasting can be carried out implicitly, and provide people with the flexibility to access the members of the parent class.
The following example can help in providing a better understanding of the process.
Example: There is an animal class that features diverse classes of animals, fish being one of them. Now, assuming that the animal class is extended by the fish class, there would be two ways of inheritance. Inheritance is one of the key aspects of Object Oriented Programming or OOP which allows one class to inherit the features of another one. This implies the derived class which is a superset of the base class. There might be more methods featured here than the base class. During the upcast, the only thing that may happen with the class interface is that it can end up losing methods rather than gaining them. As a result of this, the compiler enables upcasting without any type of special notations or explicit casts.
Composition vs Inheritance
When it comes to object-oriented programming, there is a high chance that one may end up creating and using done by just packaging methods and data together in a class, while subsequently making use of the objects present in that class. People may even use certain existing classes to develop new classes with composition. Inheritance is used comparatively rarely. While learning OPP even though inheritance does get a lot of focus, it is important that developers know its correct usage and do not try to use it simply wherever they can.
In fact, one must use it quite rarely, only for the scenarios where inheritance is actually found to be useful. Among the simplest ways to identify whether a person should use inheritance or composition is to question themselves about if they need to upcast from their new cast to the base cast. In case upcasting is a necessity then one would have to use inheritance. However, if it is not a requirement, then one must further dwell on the need for inheritance.
Explore Our Software Development Free Courses
|Blockchain Technology||React for Beginners||Core Java Basics|
Now that we know what is upcasting in Java, in this section, we dive deeper to explore what is downcasting in Java.
Downcasting is another form of object type casting and is used in appointing the subclass reference object to the parent class that is not allowed in Java. Downcast is not too difficult to understand. For instance, if there is a base class and a class that either indirectly or indirectly derives from the base class then any time an object of the base class type goes on to being typecast into a derived class, it is referred to as a downcast. Consequently, as per downcasting, one would go down the inheritance diagram by striving to take a base class object and then converting it into a derived class type. However, it is important to note that based on the code being written, downcasting may or may not make sense.
As people carry out the downcasting system, they won’t come across any type of compiler error. However, they would face java.lang.ClassCastException, which is a runtime exception. So now the question arises if downcasting is not possible in Java then why do people perform it? Simply put, downcasting can be used only in particular situations where the object referred by the parent class belongs to a subclass.
Downcasting can be extremely useful when comparing one object to another.
To check if a downcasting is valid or not, one can run
getClass() system enables the developers to understand the class of the object being passed in, and subsequently compare it with the current class. In case they are not equal, then downcasting shall not be valid and trying out this process will be pointless. The concept of downcasting majorly uses the casting of super-types to the subtypes. Such a casting process is usually done in an explicit manner. This basically implies that larger sized types are made to explicitly fit into small size types.
upGrad’s Exclusive Software Development Webinar for you –
SAAS Business – What is So Different?
Upcasting vs Downcasting
Upcasting and. Downcasting has certain very particular differences. Some of them have been briefly underlined in the following pointers:
- In Upcasting a child object is typecast to a parent object. On the other hand, the reference of the parent class object ends up passing on to the child class when it comes to downcasting.
- People can perform upcasting both explicitly and implicitly, while downcasting can only be performed explicitly.
- In the case of upcasting, people can access the variables and methods of the parent class in the child class but not the other way round. In downcasting, however, the variables and methods of both the classes are easily accessible.
- Upcasting allows access to only particular child class methods. Both when performing downcasting, all the methods and variables coming under both the classes are made accessible.
- Upcasting is always safe, with zero chances of failure. However, downcasting has risks of failing as it can throw up a ClassCastException. So what’s the fix? The instanceof operator must be used to downcast safely.
Now that you are geared with the knowledge of what is upcasting and downcasting in Java, you must be wondering, “Why is it important?”
Simply put, it gives you the tools to use a simple syntax to build complicated programs. Even though upcasting is rarely used in Java, if you want to generalize a function or property of the parent class to its subtype, you need to use typecasting. On the other hand, downcasting is used more frequently. Downcasting in Java is essential when depending on the subtype, you want to access specific subtype behaviours.
It is, nonetheless, important to keep in mind that when casting an object, we are only changing the reference type of the object and not the actual object type itself.
In-Demand Software Development Skills
Upcasting is used rarely in Java. In most cases, people use it when they have to develop a code that just deals with the parent class. When it comes to developing a code that provides access to the behaviour of the child class, downcasting tends to be used.
If you want to learn Java and earn a certification in cloud computing as well, upGrad offers an Advanced Certificate Programme in Cloud Computing. The 7.5-month online course is specifically designed for working professionals to help them gain entry into cloud computing roles.
What is Java, and how has it come into existence?
Java is a programming language that can be used to create applications that run on a computer. It is an object-oriented programming language. Java is a general-purpose computer programming language that was designed to be used in client/server environments. The Java programming language originated as a part of a research assignment to broaden advanced software for a huge form of community devices and embedded systems. James Gosling and Bill Joy developed Java at Sun Microsystems in the early 1990s. Java supports several types of data structures, including arrays, objects, strings, files and databases. It also supports one of the most widely used programming languages: C++.
What does typecasting mean in terms of Java?
Java uses typecasting to allow you to perform operations on primitive data types without having to first convert them into objects or primitives. It also allows you to create classes and objects, which are made up of fields, methods and objects. Typecasting is an important feature of the Java language because it allows programmers to avoid casting while maintaining compatibility with existing code written in other languages. Java's type system enables you to write programs that can be run on any type of computer from handheld devices to mainframes and supercomputers.
Why is downcasting important?
Downcasting is when you cast an object of one class type down into another class type for some reason. For example, if you had an employee class and wanted to set salary information for employees who worked for your company in past years. In order for this operation to work properly, the employee class must support downcasting as well as casting from one class type into another.