Simple Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • first2drown
    New Member
    • Jan 2009
    • 13

    Simple Question

    I'm reviewing for my mid term which I will be taking this evening. On the practice exam, the following question is given:
    Given the following, which line is illegal, assuming that class Watch extends class Clock?
    Clock A = new Clock();
    Watch B = new Watch();
    A=B;
    B=A;

    On the answer key, he states that B=A; is the illegal statement because a Clock is not necessarily a Watch...but that feels wrong. I feel that in this, A=B; would be the illegal statement. But I also understand that maybe I don't fully understand how an assignment operator would work in this case. Could someone please explain this to me?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Maybe you could tell us why you feel that A =B is wrong. Think memory locations. A memory location that holds a Clock can hold a Watch because a watch IS-A Clock. That is what the inheritance is-A relationship is all about.

    Now suppose we create another Clock, say QuartzTimer. Our QuartzTimer would extend Clock because we said that it IS another Clock.
    Now a memory location that can hold a Watch cannot hold a QuartzTimer This is because a QuartzTimer IS NOT a Watch. Since a QuartzTimer is Clock, we have shown that a memory location that holds a Watch does not hold all Clocks.
    A and B are pointers to memory locations to Clock and Watch objects.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by first2drown
      I'm reviewing for my mid term which I will be taking this evening. On the practice exam, the following question is given:
      Given the following, which line is illegal, assuming that class Watch extends class Clock?
      Clock A = new Clock();
      Watch B = new Watch();
      A=B;
      B=A;

      On the answer key, he states that B=A; is the illegal statement because a Clock is not necessarily a Watch...but that feels wrong. I feel that in this, A=B; would be the illegal statement. But I also understand that maybe I don't fully understand how an assignment operator would work in this case. Could someone please explain this to me?
      Your variable B can point to any clock you can easily carry around: a watch (at your wrist maybe). You most certainly can't make it point to a huge clock; you need a variable A for that; so concluding: you can't say B=A because that could accidentally make your B point to such a huge beast. (see the attachment for a typical "not a watch" ;-)

      kind regards,

      Jos
      Attached Files

      Comment

      Working...