·  JAVA – Syntax – Terms – Upcasting

 

- Info:

  - Upcasting permits an object of a subclass type (Dog) to be treated as an object of any superclass type (Animal).

  - Upcasting is done automatcily since each subclass extands all the features of superclass.

    So by treating subclass as superclass you are simply using subset of its features.

  - By casting you are not changing the object, you are just labeling (treating) it differently.

 

- Example:

  - In this example we upcast Soldier to Person, we create Object of class Soldier but treat it as if it is of class Person.

  - This means that only properties and methods defined in Person will be visible which is why we can't access 'bullets'.

  - It is not necessary to explicitly cast to Person since this is done automaticly.

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test {

      public static void main(String[] args) {

 

        Person jill = (Person) new Soldier(); //Excplicit upcasting Soldier to Person.

 

        Person john =          new Soldier(); //Implicit  upcasting Soldier to Person.

               john.attack();  

               //john.bullets = 10;           //Bullets don't exist in Person class

 

        Soldier jack        =  new Soldier();

        Person  jackPerson  =  (Person) jack; //Excplicit upcasting Soldier to Person.

        Person  jackPerson2 =           jack; //Implicit  upcasting Soldier to Person.

 

      }     

    }

    

    class Person {

      void attack() { System.out.println("Using fist."); }

    }

    

    class Soldier extends Person {

      int  bullets = 100;

      void attack() { System.out.println("Using gun."); }

    }

 

    output

    Using gun.