Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - How to cast subclass object to superclass object

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
   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...