What is the difference between throwing and downcasting relative to a class variable

What is the difference between casting and downcasting on a class variable?

For example, in the following program class, Animal contains only one method, but the Dog class contains two methods, how we apply the Dog variable to the Animal variable.

If casting is done, how can we call the Dog method using the Animal variable.

class Animal { public void callme() { System.out.println("In callme of Animal"); } } class Dog extends Animal { public void callme() { System.out.println("In callme of Dog"); } public void callme2() { System.out.println("In callme2 of Dog"); } } public class UseAnimlas { public static void main (String [] args) { Dog d = new Dog(); Animal a = (Animal)d; d.callme(); a.callme(); ((Dog) a).callme2(); } } 
+101
java casting class-variables downcasting upcasting
May 01 '14 at 18:30
source share
10 answers

Upcasting is a cast to a supertype, and downcasting is a subtype. Updates are always allowed, but they include type checking and may have a ClassCastException .

In your case, casting from Dog to Animal is an outcast because Dog is Animal . In general, you can use upcast when there is a relationship between two classes.

Downing will be something like this:

 Animal animal = new Dog(); Dog castedDog = (Dog) animal; 

Essentially, you tell the compiler that you know what type of object it actually has . The compiler will allow the conversion, but will still insert a health check at runtime to make sure the conversion makes sense. In this case, casting is possible because at run time the animal actually Dog although the static type of animal is Animal .

However, if you were to do this:

 Animal animal = new Animal(); Dog notADog = (Dog) animal; 

You will get a ClassCastException . The reason is that the animal runtime type is Animal , and therefore, when you tell the runtime to cast, it sees that animal is actually not Dog and throws a ClassCastException .

To call a superclass method, you can do super.method() or do an upcast.

To call the subclass method, you must do a downcast. As shown above, you usually risk a ClassCastException by doing this; however, you can use the instanceof operator to check the type of the object at runtime before executing the cast, which allows you to prevent ClassCastException s:

 Animal animal = getAnimal(); // Maybe a Dog? Maybe a Cat? Maybe an Animal? if (animal instanceof Dog) { // Guaranteed to succeed, barring classloader shenanigans Dog castedDog = (Dog) animal; } 
+159
May 01 '14 at 19:12
source share

The conversion and conversion was as follows:
enter image description here

Upcasting : When we want to bring a Subclass to a Superclass, we use Upcasting (or an extension). This happens automatically, no need to do anything explicitly.

Downcasting : when we want to convert a superclass to a subclass, we use downcasting (or narrowing), and downcasting is not directly possible in Java, which is clearly necessary.

 Dog d = new Dog(); Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting d.callme(); a.callme(); // It calls Dog method even though we use Animal reference. ((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly. // Internally if it is not a Dog object it throws ClassCastException 
+42
Jan 21 '16 at 7:02
source share

Speeding up and downgrading is an important part of Java, which allows us to create complex programs using simple syntax and gives us great advantages, such as polymorphism or grouping of different objects. Java allows an object of a subclass type to be processed as an object of any type of superclass. This is called a boost. Activation is done automatically, while downcasting must be done manually by the programmer , and I'm going to give my best to explain why this is so.

Upcasting and downcasting are not like casting primitives from one to the other, and I think this causes a lot of confusion when a programmer begins to study cast objects.

Polymorphism: all methods in java are virtual by default. This means that any method can be overridden when used in inheritance, if this method is not declared as final or static .

The following is an example of how getType(); works according to the type of object (Dog, Pet, Police Dog).

Suppose you have three dogs

  • A dog is a superclass.
  • Pet Dog - Pet Dog expands Dog.
  • Police Dog - A police dog expands a dog.

     public class Dog{ public String getType () { System.out.println("NormalDog"); return "NormalDog"; } } /** * Pet Dog has an extra method dogName() */ public class PetDog extends Dog{ public String getType () { System.out.println("PetDog"); return "PetDog"; } public String dogName () { System.out.println("I don't have Name !!"); return "NO Name"; } } /** * Police Dog has an extra method secretId() */ public class PoliceDog extends PetDog{ public String secretId() { System.out.println("ID"); return "ID"; } public String getType () { System.out.println("I am a Police Dog"); return "Police Dog"; } } 

Polymorphism: all methods in java are virtual by default. This means that any method can be overridden when used in inheritance, if this method is not declared as final or static. (Explanation refers to the concept of virtual tables)

Virtual table / dispatcher table. The object dispatch table will contain the addresses of the dynamically linked methods of the object. A method call is made by extracting the method address from the object dispatch table. The distribution table is the same for all objects belonging to the same class, and therefore is usually distributed between them.

 public static void main (String[] args) { /** * Creating the different objects with super class Reference */ Dog obj1 = new Dog(); ` /** * Object of Pet Dog is created with Dog Reference since * Upcasting is done automatically for us we don't have to worry about it * */ Dog obj2 = new PetDog(); ` /** * Object of Police Dog is created with Dog Reference since * Upcasting is done automatically for us we don't have to worry * about it here even though we are extending PoliceDog with PetDog * since PetDog is extending Dog Java automatically upcast for us */ Dog obj3 = new PoliceDog(); } obj1.getType(); 

Print Normal Dog

  obj2.getType(); 

Seal Pet Dog

  obj3.getType(); 

Fingerprints of Police Dog

Downside must be done manually by the programmer

When you try to call the secretID(); method secretID(); to obj3 , which is a PoliceDog object , but referencing Dog , which is a superclass in the hierarchy, it throws an error because obj3 does not have access to secretId() . To call this method, you need to downcast that obj3 manually, PoliceDog

  ( (PoliceDog)obj3).secretID(); 

which prints ID

Similarly, to call dogName(); in the PetDog class, you need to compress obj2 in PetDog , since obj2 refers to Dog and does not have access to the dogName(); method dogName();

  ( (PetDog)obj2).dogName(); 

Why is it that the upstream is automatic, but downcasting has to be manual? Well, you see, a promotion may never fail. But if you have a group of different dogs, and you want to be dumped all of them, they had the possibility that some of these Dogs are of different types, i.e. PetDog , PoliceDog , and the process fails by throwing a ClassCastException .

It is for this reason that you need to delete your objects manually if you pointed your objects to the type of superclass.

Note. Here, referring to the fact that you do not change the memory address of your projects, when you omit it, it still remains the same, you simply group them by a certain type in this case Dog

+27
Sep 27 '15 at 22:46
source share

I know this question asked a long time ago, but for new users of this question. Please read this article for a full description of increasing, downcasting, and using instanceof.

  • There is no need to manually adjust, this happens on its own:

    Mammal m = (Mammal)new Cat(); equal to Mammal m = new Cat();

  • But downcasting should always be done manually:

     Cat c1 = new Cat(); Animal a = c1; //automatic upcasting to Animal Cat c2 = (Cat) a; //manual downcasting back to a Cat 

Why is it that the upstream is automatic, but downcasting has to be manual? Well, you see, a promotion may never fail. But if you have a group of different animals and you want to surpass them all in Cat, then there is a chance that some of these animals are actually Dogs, and the process fails by throwing a ClassCastException. Here you should introduce the useful function "instanceof" , which checks if the object is an instance of some class.

  Cat c1 = new Cat(); Animal a = c1; //upcasting to Animal if(a instanceof Cat){ // testing if the Animal is a Cat System.out.println("It a Cat! Now i can safely downcast it to a Cat, without a fear of failure."); Cat c2 = (Cat)a; } 

For more information, please read this article.

+12
Nov 10 '15 at 5:30
source share

Better try this method to enhance, it's easy to understand:

 /* upcasting problem */ class Animal { public void callme() { System.out.println("In callme of Animal"); } } class Dog extends Animal { public void callme() { System.out.println("In callme of Dog"); } public void callme2() { System.out.println("In callme2 of Dog"); } } public class Useanimlas { public static void main (String [] args) { Animal animal = new Animal (); Dog dog = new Dog(); Animal ref; ref = animal; ref.callme(); ref = dog; ref.callme(); } } 
+6
Sep 19 '14 at 13:40
source share

Maybe this table helps. Call callme() of the Parent class or the Child class. As a principle:

UPDATE → Hiding

DOWNCASTING → Identification

enter image description here

enter image description here

enter image description here

+5
Aug 29 '16 at 10:08 on
source share

Parent: Car
Baby: Figo
Car c1 = new Figo ();

=====
Converting to the base type: -
Method: Object c1 will refer to Class Methods (Figo - The method must be redefined) because the class "Figo" is indicated with "new".
Instance variable: object c1 will refer to the instance variable of the declaration class ("car").

When the declaration class is parent and the object is created from a descendant, then implicit casting occurs, which is “Upcasting”.

======
Lowering cast: -
Figo f1 = (Figo) c1; //
Method: The object f1 will refer to the class method (figo), since the initial object c1 is created with the class "Figo". but after the listing is done, methods that are present only in the "Figo" class can also be passed to the variable f1.
Instance variable: object f1 will not refer to an instance variable of class Decl1 of object c1 (the declaration class for c1 is CAR), but with downcasting, it will refer to instance variables of class Figo.

======
Usage: When an Object has a Child class and a declaration class, the Parent and Child class wants to access the Instance variable of this class, not the parent class, then this can be done using "Downcasting".

+2
Aug 07 '15 at 6:40
source share

1.- Update.

By doing upcasting, you define a tag of some type that points to a subtype object (Type and subtype can be called a class and a subclass if you feel more comfortable ...).

 Animal animalCat = new Cat(); 

Which means that such an animalCat tag will have functionality (methods) only of type Animal, because we declared it as an Animal type, and not as a Cat type.

We are allowed to do this in a “natural / implicit / automatic” way, at compile time or at run time, mainly because Cat inherits some of its functions from Animal; e.g. move (). (At least a cat is an animal, isn't it?)

2.- Downing.

But what happens if we need to get Cat functionality from our Animal type tag ?.

Since we created the animalCat tag pointing to the Cat object, we need a way to call the methods of the Cat object from our animalCat tag in a rather smart way.

We call this procedure Downcasting, and we can only do this at run time.

Time for some code:

 public class Animal { public String move() { return "Going to somewhere"; } } public class Cat extends Animal{ public String makeNoise() { return "Meow!"; } } public class Test { public static void main(String[] args) { //1.- Upcasting // __Type_____tag________object Animal animalCat = new Cat(); //Some animal movement System.out.println(animalCat.move()); //prints "Going to somewhere" //2.- Downcasting //Now you wanna make some Animal noise. //First of all: type Animal hasn't any makeNoise() functionality. //But Cat can do it!. I wanna be an Animal Cat now!! //___________________Downcast__tag_____ Cat method String animalNoise = ( (Cat) animalCat ).makeNoise(); System.out.println(animalNoise); //Prints "Meow!", as cats usually done. //3.- An Animal may be a Cat, but a Dog or a Rhinoceros too. //All of them have their own noises and own functionalities. //Uncomment below and read the error in the console: // __Type_____tag________object //Cat catAnimal = new Animal(); } } 
+2
Oct 06 '18 at 19:02
source share

upcasting means casting an object into a supertype, while downcasting means casting a subtype.

In java, raising is not required, as it is done automatically. And this is commonly called implicit casting. You can indicate it so that it makes others understand.

Thus recording

 Animal a = (Animal)d; 

or

 Animal a = d; 

leads to exactly the same point and in both cases callme() from Dog will be executed.

Instead, downcasting is required because you defined a as an Animal object. You currently know this Dog , but java has no guarantees. Actually at runtime it may be different and java will throw a ClassCastException , this will happen. Of course, this is not the case of your example. If you did not add a to Animal , java could not even compile the application, because Animal does not have a callme2() method.

In your example, you cannot reach the callme() code from Animal from UseAnimlas (because Dog rewrite it), unless the method is as follows:

 class Dog extends Animal { public void callme() { super.callme(); System.out.println("In callme of Dog"); } ... } 
+1
May 01 '14 at 19:26
source share

We can create an object for Downcasting. In this type too .: calling base class methods

 Animal a=new Dog(); a.callme(); ((Dog)a).callme2(); 
0
Feb 22 '16 at 7:09
source share



All Articles