How to cast subclass object to superclass object

30,386

Solution 1

A superclass cannot know subclasses methods.

Think about it this way:

  • You have a superclass Pet

  • You have two subclasses of Pet, namely: Cat, Dog

  • Both subclasses would share equal traits, such as speak
  • The Pet superclass is aware of these, as all Pets can speak (even if it doesn't know the exact mechanics of this operation)
  • A Dog however can do things that a cat cannot, i.e. eatHomework
  • If we were to cast a Dog to a Pet, the observers of the application would not be aware that the Pet is in fact a Dog (even if we know this as the implementers)
  • Considering this, it would not make sense to call eatHomework of a Pet

You could solve your problem by telling the program that you know sup is of type subclass

public class Testing
{    
   public static void main(String args[])
   {
      subclass sub = new subclass();
      superclass sup = (superclass) sub; 
      subclass theSub = (subclass) sup;
      theSub.displaySub();
   }
}

You could solve the problem altogether by doing something like this:

public class superclass
{
    public void display()
    }
        System.out.println("Display Superclass");
    }
}

public class subclass extends superclass
{
    public void display()
    {  
        System.out.println("Display Subclass");
    }
}

public class Testing
{    
   public static void main(String args[])
   {
      subclass sub = new subclass();
      superclass sup = (superclass) sub; 
      sup.display();
   }
}

check out this tutorial on more info: overrides

Solution 2

Take a look at java inheritance: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

A subclass can use superclass methods, but a superclass cannot use subclass methods. If you want to call a superclass to use a subclass method, you must first cast the superclass instance to the subclass. (subclass) sup

Share:
30,386
Admin
Author by

Admin

Updated on June 03, 2020

Comments

  • Admin
    Admin almost 4 years

    i have 2 classes, called superclass and subclass, i tried to cast the subclass object to superclass, but its seems does not work when i want to use the subclass object from the superclass. Please help to explain. Thanks. These are the code:-

    public class superclass
    {
        public void displaySuper()
        }
            System.out.println("Display Superclass");
        }
    }
    
    public class subclass extends superclass
    {
        public void displaySub()
        {  
            System.out.println("Display Subclass");
        }
    }
    
    
    public class Testing
    {    
       public static void main(String args[])
       {
          subclass sub = new subclass();
          superclass sup = (superclass) sub; 
    

    when i tried to use the displaySub() from the subclass get error

          sup.displaySub(); //the displaySub method cant found
       }
    }