Results 1 to 3 of 3
  1. #1
    The Vip is offline Member
    Join Date
    Jul 2016
    Posts
    3
    Rep Power
    0

    Question Is is possible to cast one class to another?

    There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C) B;

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Is is possible to cast one class to another?

    casting is done to variables that reference objects or to primitives that can be changed to the target type. If a variable refers to an object that is an instance of the target cast, then it can be cast.

    Rewording your question:
    C refToC = (C) refToB;
    would work if refToB was given a value of a C object:
    B refToB = new C(); // refToB refers to a C object
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: Is is possible to cast one class to another?

    Draw a tree (upside down, because math folks are funny); the top of the tree (the root) is named Object (the mother of all classes). All other classes dangle somewhere below that root (Object) and form the tree. Two class B and D can be cast to each other if they are on a same path of the tree. If the path from D to B is oriented towards the root, it is called an 'upcast' and you don't need to explicitly cast. Otherwise (a 'downcast') an explicit cast is needed. Interfaces complicate this stuff somewhat ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. Class cast
    By bkraut in forum Advanced Java
    Replies: 4
    Last Post: 02-23-2012, 10:27 PM
  2. Class Cast exception
    By henry123 in forum Advanced Java
    Replies: 4
    Last Post: 02-15-2011, 11:42 AM
  3. Class Inheritance Cast
    By letdoit in forum New To Java
    Replies: 1
    Last Post: 02-03-2011, 06:14 AM
  4. Class cast issue
    By AedonetLIRA in forum New To Java
    Replies: 5
    Last Post: 11-19-2010, 04:34 PM
  5. Cast own class to FrameView
    By Luxpsycho in forum AWT / Swing
    Replies: 0
    Last Post: 07-16-2010, 10:13 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •