Results 1 to 5 of 5

Thread: Casting Problem

  1. #1
    Join Date
    Aug 2011
    Location
    salt Lake City, Utah
    Posts
    10
    Rep Power
    0

    Question Casting Problem

    I am experiencing a casting problem and I do not fully understand the reason why what I am doing is not working. Below is my code. I will explain the problem after the code.

    Java Code:
    package com.nathandelane.problems.casting;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * My casting problem.
     * @author nathanlane
     *
     */
    public final class Main {
    
      /**
       * Base class.
       * @author nathanlane
       *
       */
      protected class VeryBaseClass {
    
        private final Map<String, Object> collection;
    
        public VeryBaseClass() {
          collection = new HashMap<String, Object>();
        }
    
        protected void setItem(final String name, final Object value) {
          collection.put(name, value);
        }
    
        protected Object getItem(final String name) {
          return collection.get(name);
        }
    
      }
    
      /**
       * Intermediary class.
       * @author nathanlane
       *
       */
      protected class IntermediaryClass extends VeryBaseClass {
    
        private static final String MY_AGE_KEY = "My Age";
    
        public IntermediaryClass() {
          super();
        }
    
        public void setMyAge(final Integer age) {
          super.setItem(MY_AGE_KEY, age);
        }
    
        public Integer getMyAge() {
          return (Integer) super.getItem(MY_AGE_KEY);
        }
    
      }
    
      protected class TopLevelClass extends IntermediaryClass {
    
        private static final String MY_HOME_TOWN_KEY = "My Home Town";
    
        public TopLevelClass() {
          super();
        }
    
        public void setMyHomeTown(final String homeTown) {
          super.setItem(MY_HOME_TOWN_KEY, homeTown);
        }
    
        public String getMyHomeTown() {
          return (String) super.getItem(MY_HOME_TOWN_KEY);
        }
    
      }
    
      private VeryBaseClass baseClass;
    
      private Main() {
        baseClass = new VeryBaseClass();
    
        final Integer myAge = 30;
    
        log(String.format("Setting my age to %1$d", myAge));
    
        ((IntermediaryClass)baseClass).setMyAge(myAge);
    
        log(String.format("Getting my age...%1$d", ((IntermediaryClass)baseClass).getMyAge()));
    
        final String myHomeTown = "Sugarhouse";
    
        log(String.format("Setting my home town to %1$s", myHomeTown));
    
        ((TopLevelClass)baseClass).setMyHomeTown("myHomeTown");
    
        log(String.format("Getting my home town...%1$s", ((TopLevelClass)baseClass).getMyHomeTown()));
      }
    
      /**
       * Program entry point.
       * @param args
       */
      public static void main(String[] args) {
        new Main();
      }
    
      private static void log(final String message) {
        System.out.println(message);
      }
    
    }
    The problem seems to be that I don't understand casting, but on the contrary, I believe I do. Now if a class extends another class, then should I not be able to cast seamlessly to the class that extends the other class. For example:

    given: A
    given: B : A
    given: C : A

    therefore B is A AND C is A

    so:
    A a = new B();
    is valid and correct.

    also:
    A a = new C();
    is valid and correct.

    The result of my actual code above, however, is:

    Java Code:
    Setting my age to 30
    Exception in thread "main" java.lang.ClassCastException: com.nathandelane.problems.casting.Main$VeryBaseClass cannot be cast to com.nathandelane.problems.casting.Main$IntermediaryClass
    	at com.nathandelane.problems.casting.Main.<init>(Main.java:86)
    	at com.nathandelane.problems.casting.Main.main(Main.java:104)
    Can anybody please explain this?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Casting Problem

    Try not nesting the classes. Ie make them wll top level.

    If that makes the error go away consider what nesting the classes means.

  3. #3
    javin.paul is offline Member
    Join Date
    Oct 2011
    Posts
    35
    Rep Power
    0

    Default Re: Casting Problem

    you can not cast super class into sub class , here "baseClass" represent object of VeryBaseClass which is super class.

  4. #4
    Join Date
    Aug 2011
    Location
    salt Lake City, Utah
    Posts
    10
    Rep Power
    0

    Thumbs up Re: Casting Problem

    Quote Originally Posted by javin.paul View Post
    you can not cast super class into sub class , here "baseClass" represent object of VeryBaseClass which is super class.
    Thanks. A coworker explained it to me like this as well:

    Given:

    A
    B : A
    C : B

    The possible references and objects are:

    Reference -> Object
    A -> A, B, C
    B -> B, C
    C -> C

    So ((B)A).methodFromB() is not possible. I later learned that what appeared to be a mysterious function in some other code was a result of me setting A to an instance of B initially, then when I attempted to cast to C, I was seeing the problem occur, but when I (thought) I was casting to B I wasn't. The test code above proved that I was wrong about my assumption, but it took me a while to figure it out. Thanks javin.paul -- that was the answer I needed.

  5. #5
    Join Date
    Aug 2011
    Location
    salt Lake City, Utah
    Posts
    10
    Rep Power
    0

    Smile Re: Casting Problem

    Here is some solution code, which reveals what my assumptions were and how casting really works. Note that this has nothing to do with nested classes. The scope for the nested classes is different in this example just to simplify it a little bit:

    Java Code:
    package com.nathandelane.problems.casting;
    
    /**
     * This is my casting problem, solved.
     * @author nathanlane
     *
     */
    public class CastingProblemSolved {
    
      static class A {
    
        public void methodFromA() {
          System.out.println("Calling method from A.");
        }
    
      }
    
      static class B extends A {
    
        public void methodFromB() {
          System.out.println("Calling method from B.");
        }
    
      }
    
      static class C extends B {
    
        public void methodFromC() {
          System.out.println("Calling method from C.");
        }
    
      }
    
      public static void main(String[] args) {
        // Creating an instance of A using class A.
        final A simpleAInstance = new A();
        // Showing that I have access to A.methodFromA().
        simpleAInstance.methodFromA();
    
        // Showing that I don't have access to B methods.
        try {
          ((B)simpleAInstance).methodFromB();
        } catch(Exception e) {
          System.out.println("Could not cast to B because it is an upper cast from A: ((B)A) is not allowed.");
        }
    
        // Creating an instance of A using class B.
        final A simpleBInstance = new B();
        // Showing that I have access to A.methodFromA() and B.methodFromB().
        simpleBInstance.methodFromA();
        ((B)simpleBInstance).methodFromB();
    
        // Showing that I don't have access to C methods.
        try {
          ((C)simpleBInstance).methodFromC();
        } catch(Exception e) {
          System.out.println("Could not cast to C because it is an upper cast from B: ((C)B) is not allowed.");
        }
    
        // Creating an instance of A using class C.
        final A simpleCInstance = new C();
        // Showing that I have access to A.methodFromA(), B.methodFromB(), and C.methodFromC().
        simpleCInstance.methodFromA();
        ((B)simpleCInstance).methodFromB();
        ((C)simpleCInstance).methodFromC();
      }
    
    }
    The output of this program is:

    Java Code:
    Calling method from A.
    Could not cast to B because it is an upper cast from A: ((B)A) is not allowed.
    Calling method from A.
    Calling method from B.
    Could not cast to C because it is an upper cast from B: ((C)B) is not allowed.
    Calling method from A.
    Calling method from B.
    Calling method from C.
    Thanks again.

Similar Threads

  1. casting an int
    By droidus in forum New To Java
    Replies: 1
    Last Post: 09-07-2011, 07:38 PM
  2. Casting classX to classX problem
    By no-one in forum Advanced Java
    Replies: 5
    Last Post: 03-17-2011, 05:39 PM
  3. Casting problem
    By Lil_Aziz1 in forum New To Java
    Replies: 2
    Last Post: 05-29-2010, 08:13 PM
  4. Casting
    By zzpprk in forum Advanced Java
    Replies: 13
    Last Post: 08-13-2009, 08:59 PM
  5. Casting problem
    By John_28 in forum New To Java
    Replies: 6
    Last Post: 05-14-2008, 12:29 PM

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
  •