Type casting objects in java

What is Type Casting in Java? Casting one Class to other class or interface Example

Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object-oriented programming language and supports b oth Inheritance and Polymorphism, It’ s easy that Super class reference variable is pointing to SubClass objects but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to SubClass object. This means you can not call a method that is declared in the subclass. In order to do that, you first need to cast t he Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in the next section.

Type casting also comes with the risk of ClassCastException in Java, which is quite common with a method that accepts Object type and later types cast into more specific types.

Читайте также:  Java утечки памяти примеры

We will see when ClassCastException comes during type casting an d How to avoid it in the coming section of this article. Another worth noting point here is that from Java 5 onwards you can use Generics to write type-safe code to r educe the amount of type casting in Java which also reduces the risk of java.lang.ClassCastException at runtime.

What is Type Casting in Java? Up Casting and Down Cast

From the first paragraph, we pretty much know What is type casting in Java. Anyway, In simple words, type casting is a process of converting on e type, whi ch cou ld be a class or interface t o another, But as per rules of Java programming language, only classes or i nterfaces (collectively known as Type) from the same type hierarchy can be cast or converted into each other.

If you try to cast two objects which don’t share same type hierarchy, i.e. there is no parent-child relationship bet ween them, y ou wil l get compile time error. On the other hand, if you typecast objects fr om same type hierarchy but the object which you are casting are not of the same type on which you are casting then it will throw ClassCastException in Java.

Some people may ask why do you need type casting? well, you need type casting to get access to fields and methods declared on the target type or class. You can not access them with any other type. Let’s see a simple example of type casting in Java with two classes Base and Derived which share the same type hierarchy.

Читайте также:  Ссылка на страницу пользователя html

Type casting example in Java

In this Example of type casting in Java, we have two classes, Base , and Derived . Derived class extends Base i.e. Base is a Super class and Derived is a Subclass. So their type hierarchy looks like the following tree :

Источник

Type Casting in Java

If you want to be a programmer in any language, then type casting variables is something that you should definitely be very familiar with.

What is Type Casting in Java?

Type casting means taking an Object of one particular type and “turning it into” another Object type. This process is called type casting a variable.

This topic is not specific to Java, as many other programming languages support casting of their variable types. But, as with other languages, in Java you cannot cast any variable to any random type.

What are the Rules behind Casting Variables?

It’s fairly simple, you remember our talk about how everything in Java is an Object, and any Object you create extends from Object? This was inheritance, and this is important to understand when dealing with casting.

If you are going to cast a variable, you’re most likely doing what’s known as a downcast. This means that you’re taking the Object and casting it into a more “specific” type of Object. Here’s an example:

Object aSentenceObject = "This is just a regular sentence"; String aSentenceString = (String)aSentenceObject;

You see what we’ve done here? Since the type Object is a very broad type for a variable, we are “downcasting” the variable to be a String type. Now, the question is, is this legal? Well, you can see that the value stored in the aSentenceObject is just a plain old String , so this cast is perfectly legal. Let’s look at the reverse scenario, an “upcast”:

String aSentenceString = "This is just another regular sentence"; Object aSentenceObject = (Object)aSentenceString;

Here we are taking a variable with a more specific type ( String ) and casting it to a variable type that’s more generic ( Object ). This is also legal, and really, it is always legal to upcast.

What are the benefits of casting variables?

There are times when you want to get more specific functionality out of a generic Object. For example, in my line of work, I deal with web applications, and I’m always dealing with something called a “model”. This “model” represents data that I want to display on a webpage, and the model is essentially a generic Map . The Map stores key/value pairs, where the key is a String and the value is usually just the generic Object type. So, an example of what would appear in this model would be:

“name” -> “Trevor Page”
“email” -> “tpage@ecosim.ca”
“birthday” -> “07-01-83”

Here’s what that Map would look like in code:

This Map is a candidate for casting, and here’s how we would deal with the casting:

String name = (String)model.get("name"); String email = (String)model.get("email"); Date birthday = (Date)model.get("birthday");

You see how we did three separate casts there? Since all the objects stored in the map are of type Object , this means that they are very generic and could most likely be downcasted. Since we know that the “name” is a String, and the “email” is a String, and the “birthday” is a Date, we can do these three downcasts safely.

This would then give us more flexibility with those three variables, because now we have an actual birthday Date object, so we have access to methods like getTime() instead of just the default Object methods.

This is quite a valuable approach to storing Object s in a Map , because if we had created the Map with something more specific than Object as the value, then we would be constrained to only storing Object s of that specific type (and its sub-classes).

What are the downsides to Casting?

Well, there is a certain amount of risk that goes along with downcasting your variables. If you were to try to cast something like a Date object to an Integer object, then you’ll get a ClassCastException . This is what’s known as a run-time exception, as it’s really only detectable when your code is running. So, unless you’re doing something with error handling, then your program will likely exit or you’ll get an ugly error message on your webpage.

So just make sure that if you are doing any downcasting, that you’re well aware of the type of object you’ll be casting.

The Best 7 Java Programming Resources

Alright, so if you’re read this far down the article, then you’re clearly interested in learning how to code. We actually have a free guide that outlines the best 7 resources for Java programmers.

When you sign up you’ll receive the guide immediately and you’ll also receive a few emails a week that will help you speed up your Java learning process so you can get up and running as fast as possible.

Go ahead an click the button below to get started!

Summary

To sum up, casting is a very useful mechanism that allows you to write more generic code that will allow you to handle many coding situations. But this mechanism can introduce some risk if you’re not careful with what you will be casting.

Источник

Приведение типов объектов в Java

Система типов Java состоит из двух типов типов: примитивы и ссылки.

Мы рассмотрели примитивные преобразования вthis article, и здесь мы сосредоточимся на приведении ссылок, чтобы получить хорошее представление о том, как Java обрабатывает типы.

Дальнейшее чтение:

Основы Java Generics

Краткое введение в основы Java Generics.

Java экземпляр оператора

Узнайте об операторе instanceof в Java

2. Примитив против Ссылка

Хотя примитивные преобразования и приведение ссылочных переменных могут выглядеть одинаково, они довольноdifferent concepts.

В обоих случаях мы «превращаем» один тип в другой. Но в упрощенном виде примитивная переменная содержит свое значение, а преобразование примитивной переменной означает необратимые изменения ее значения:

double myDouble = 1.1; int myInt = (int) myDouble; assertNotEquals(myDouble, myInt);

После преобразования в приведенном выше примере переменнаяmyInt равна1, и мы не можем восстановить из нее предыдущее значение1.1.

Reference variables are different; ссылочная переменная относится только к объекту, но не содержит самого объекта.

Приведение ссылочной переменной не затрагивает объект, к которому она относится, а только помечает этот объект другим способом, расширяя или сужая возможности для работы с ним. Upcasting narrows the list of methods and properties available to this object, and downcasting can extend it.с

Ссылка похожа на дистанционное управление объектом. Пульт дистанционного управления имеет больше или меньше кнопок в зависимости от его типа, а сам объект хранится в куче. Когда мы выполняем кастинг, мы меняем тип пульта дистанционного управления, но не меняем сам объект.

3. Апкастинг

Casting from a subclass to a superclass is called upcasting. Как правило, преобразование выполняется неявным образом.

Обновление тесно связано с наследованием — еще одна ключевая концепция в Java. Обычно используются ссылочные переменные для ссылки на более конкретный тип. И каждый раз, когда мы делаем это, происходит неявное обновление.

Чтобы продемонстрировать апкастинг, давайте определим классAnimal:

Источник

Оцените статью