Java downcasting что это

What is Upcasting and Downcasting in Java

Perhaps in your daily Java coding, you see (and use) upcasting and downcasting occasionally. You may hear the terms ‘casting’, ‘upcasting’, ‘downcasting’ from someone or somewhere, and you may be confused about them.

As you read on, you will realize that upcasting and downcasting are really simple.

Before we go into the details, suppose that we have the following class hierarchy:

Mammal > Animal > Dog, Cat

Mammal is the super interface:

public abstract class Animal implements Mammal < public void eat() < System.out.println("Eating. "); >public void move() < System.out.println("Moving. "); >public void sleep() < System.out.println("Sleeping. "); >>
public class Dog extends Animal < public void bark() < System.out.println("Gow gow!"); >public void eat() < System.out.println("Dog is eating. "); >> public class Cat extends Animal < public void meow() < System.out.println("Meow Meow!"); >>

1. What is Upcasting in Java?

Upcasting is casting a subtype to a supertype, upward to the inheritance tree. Let’s see an example:

Dog dog = new Dog(); Animal anim = (Animal) dog; anim.eat();

Here, we cast the Dog type to the Animal type. Because Animal is the supertype of Dog , this casting is called upcasting.

Note that the actual object type does not change because of casting. The Dog object is still a Dog object. Only the reference type gets changed. Hence the above code produces the following output:

Upcasting is always safe, as we treat a type to a more general one. In the above example, an Animal has all behaviors of a Dog .

This is also another example of upcasting:

Mammal mam = new Cat(); Animal anim = new Dog();

2. Why is Upcasting in Java?

Generally, upcasting is not necessary. However, we need upcasting when we want to write general code that deals with only the supertype. Consider the following class:

public class AnimalTrainer < public void teach(Animal anim) < anim.move(); anim.eat(); >>

Here, the teach() method can accept any object which is subtype of Animal . So objects of type Dog and Cat will be upcasted to Animal when they are passed into this method:

Dog dog = new Dog(); Cat cat = new Cat(); AnimalTrainer trainer = new AnimalTrainer(); trainer.teach(dog); trainer.teach(cat);

3. What is Downcasting in Java?

Downcasting is casting to a subtype, downward to the inheritance tree. Let’s see an example:

Animal anim = new Cat(); Cat cat = (Cat) anim;

Here, we cast the Animal type to the Cat type. As Cat is subclass of Animal , this casting is called downcasting.

Читайте также:  Java чат бот телеграм

Unlike upcasting, downcasting can fail if the actual object type is not the target object type. For example:

Animal anim = new Cat(); Dog dog = (Dog) anim;

This will throw a ClassCastException because the actual object type is Cat . And a Cat is not a Dog so we cannot cast it to a Dog .

The Java language provides the instanceof keyword to check type of an object before casting. For example:

if (anim instanceof Cat) < Cat cat = (Cat) anim; cat.meow(); >else if (anim instanceof Dog)

So if you are not sure about the original object type, use the instanceof operator to check the type before casting. This eliminates the risk of a ClassCastException thrown.

4. Why is Downcasting in Java?

Downcasting is used more frequently than upcasting. Use downcasting when we want to access specific behaviors of a subtype.

Consider the following example:

public class AnimalTrainer < public void teach(Animal anim) < // do animal-things anim.move(); anim.eat(); // if there's a dog, tell it barks if (anim instanceof Dog) < Dog dog = (Dog) anim; dog.bark(); >> >

Here, in the teach() method, we check if there is an instance of a Dog object passed in, downcast it to the Dog type and invoke its specific method, bark() .

Okay, so far you have got the nuts and bolts of upcasting and downcasting in Java. Remember:

  • Casting does not change the actual object type. Only the reference type gets changed.
  • Upcasting is always safe and never fails.
  • Downcasting can risk throwing a ClassCastException , so the instanceof operator is used to check type before casting.

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

Dog dog = new Dog();
Animal anim = dog; //Enough
anim.eat(); // fails if eat() is not overridden. Try!!
two references anim and dog, are there now. reference does not ‘change’.
Entire article is absolute trash!

The Cat and Dog class below implement the Animal interface. All animals have names, but only dogs do tricks. Implement the describe method, using the instanceof operator to test whether the given animal is a dog. If so, return the name, a space, and the trick that the dog can do, such as «Helmut barks at the moon». If it is any other kind of animal, return the name, a space, and «has no tricks».

Читайте также:  Include php file with variables

Chào Duc,
Downcasting được dùng thường xuyên em ạ. Phổ biến trong hàm equals(). Em xem ví dụ ở bài viết này: codejava.net/. /.

Đọc qua bài của anh em vẫn chưa hiểu tại sao lại phải cần sử dụng downcasting? Tại sao không sử dụng luôn upcasting đi?

Nếu được anh có thể cho em một vài ví dụ cụ thể không?

Your example is illogical — if you’re going to use real-world examples, the words have meanings. All mammals are animals, but not all animals are mammals. You should start with Animal > Mammal > Dog.

Источник

Upcasting Vs Downcasting in Java

Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed.
Just like the data types, the objects can also be typecasted. However, in objects, there are only two types of objects, i.e. parent object and child object. Therefore, typecasting of objects basically means that one type of object (i.e.) child or parent to another. There are two types of typecasting. They are:

  1. Upcasting: Upcasting is the typecastingof a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can access the overridden methods.
  2. Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.

The following image illustrates the concept of upcasting and downcasting:

Example: Let there be a parent class. There can be many children of a parent. Let’s take one of the children into consideration. The child inherits the properties of the parent. Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child’s properties. However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it’s not possible, the compiler throws a ClassCastException.
Let’s understand the following code to understand the difference:

Читайте также:  Поиск пропавших котов - сценарий

Источник

Приведение типов. Расширение и сужение

— Привет, Амиго! Тема сегодняшней лекции – расширение и сужение типов. С расширением и сужением примитивных типов ты познакомился уже давно. На 10 уровне. Сегодня мы расскажем, как это работает для ссылочных типов, т.е. для объектов классов.

Тут все довольно просто на самом деле. Представь себе цепочку наследования класса: класс, его родитель, родитель родителя и т.д. до самого класса Object. Т.к. класс содержит все методы класса, от которого он был унаследован , то объект этого класса можно сохранить в переменную любого из его типов родителей.

class Animal < public void doAnimalActions()<>> class Cat extends Animal < public void doCatActions()<>> class Tiger extends Cat < public void doTigerActions()<>>
public static void main(String[] args) < Tiger tiger = new Tiger(); Cat cat = new Tiger(); Animal animal = new Tiger(); Object obj = new Tiger(); >

Теперь рассмотрим, что же такое расширение и сужение типов.

Если в результате присваивания мы двигаемся по цепочке наследования вверх (к типу Object), то это — расширение типа (оно же — восходящее преобразование или upcasting), а если вниз, к типу объекта, то это — сужение типа (оно же — нисходящее преобразование или downcasting).

Движение вверх по цепочке наследования называется расширением, поскольку оно приводит к более общему типу. Но при этом теряется возможность вызвать методы, которые были добавлены в класс при наследовании.

public static void main(String[] args) < Object obj = new Tiger(); Animal animal = (Animal) obj; Cat cat = (Cat) obj; Tiger tiger = (Tiger) animal; Tiger tiger2 = (Tiger) cat; >

При этом Java-машина выполняет проверку, а действительно ли данный объект унаследован от Типа, к которому мы хотим его преобразовать.

Источник

Java downcasting что это

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

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