[java] Casting objects in Java

I'm confused about what it means to cast objects in Java.

Say you have...

Superclass variable = new Subclass object();
(Superclass variable).method();

What is happening here? Does the variable type change, or is it the object within the variable that changes? Very confused.

This question is related to java object casting

The answer is


Have a look at this sample:

public class A {
  //statements
}

public class B extends A {
  public void foo() { }
}

A a=new B();

//To execute **foo()** method.

((B)a).foo();

Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:

class Parent{
   void method(){ System.out.print("this is the parent"); }
}

class Child extends Parent{
   @override
   void method(){ System.out.print("this is the child"); }
}
...
Parent o = new Child();
o.method();
((Child)o).method();  

The two method call will both print : "this is the child".


Lets say you have Class A as superclass and Class B subclass of A.

public class A {

    public void printFromA(){
        System.out.println("Inside A");
    }
}
public class B extends A {

    public void printFromB(){
        System.out.println("Inside B");
    }

}

public class MainClass {

    public static void main(String []args){

        A a = new B();
        a.printFromA(); //this can be called without typecasting

        ((B)a).printFromB(); //the method printFromB needs to be typecast 
    }
}

For example you have Animal superclass and Cat subclass.Say your subclass has speak(); method.

class Animal{

  public void walk(){

  }

}

class Cat extends Animal{

  @Override
  public void walk(){

  }

  public void speak(){

  }

  public void main(String args[]){

    Animal a=new Cat();
    //a.speak(); Compile Error
    // If you use speak method for "a" reference variable you should downcast. Like this:

    ((Cat)a).speak();
  }

}

Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()

The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.

So:

Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ? This is called casting


Superclass variable = new subclass object();
This just creates an object of type subclass, but assigns it to the type superclass. All the subclasses' data is created etc, but the variable cannot access the subclasses data/functions. In other words, you cannot call any methods or access data specific to the subclass, you can only access the superclasses stuff.

However, you can cast Superclassvariable to the Subclass and use its methods/data.


In this example your superclass variable is telling the subclass object to implement the method of the superclass. This is the case of the java object type casting. Here the method() function is originally the method of the superclass but the superclass variable cannot access the other methods of the subclass object that are not present in the superclass.


The example you are referring to is called Upcasting in java.

It creates a subclass object with a super class variable pointing to it.

The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.

For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine

class Machine{

    public void start(){

        System.out.println("Machine Started");
    }
}

class Camera extends Machine{
     public void start(){

            System.out.println("Camera Started");
        }
     public void snap(){
         System.out.println("Photo taken");
     }
 }
Machine machine1 = new Camera();
machine1.start();

If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be "Camera Started" The variable is still a reference of Machine class. If you attempt machine1.snap(); the code will not compile

The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap() wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start()). You can not ask a machine reference to take a snap. :)


in some cases we can’t provide guarantee for the type of elements or objects present inside our collection or wise, at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.

Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array. to achieve type safety we have to use typecasting.


Sometimes you will like to receive as argument a Parent reference and inside you probably want to do something specific of a child.

abstract class Animal{
 public abstract void move();
}
class Shark extends Animal{
 public void move(){
  swim();
 }
 public void swim(){}
 public void bite(){}
}
class Dog extends Animal{
 public void move(){
  run();
 }
 public void run(){}
 public void bark(){}
}

...

void somethingSpecific(Animal animal){
 // Here you don't know and may don't care which animal enters
 animal.move(); // You can call parent methods but you can't call bark or bite.
 if(animal instanceof Shark){
  Shark shark = (Shark)animal;
  shark.bite(); // Now you can call bite!
 }
 //doSomethingSharky(animal); // You cannot call this method.
}

...

In above's method you can pass either Shark or Dog, but what if you have something like this:

void doSomethingSharky(Shark shark){
 //Here you cannot receive an Animal reference
}

That method can only be called by passing shark references So if you have an Animal (and it is deeply a Shark) you can call it like this:

Animal animal...
doSomethingSharky((Shark) animal)

Bottom line, you can use Parent references and it is usually better when you don't care about the implementation of the parent and use casting to use the Child as an specific object, it will be exactly the same object, but your reference know it, if you don't cast it, your reference will point to the same object but cannot be sure what kind of Animal would it be, therefore will only allow you to call known methods.