×

Loading...

Topic

  • 工作学习 / IT技术讨论 / A question about down-casting
    Question: Is "a1" an instance of "Animal", or "Snake" ? why?

    If I remove "abstract" from the definition of class Animal, what's the running result ?

    //: TestAnimal.java
    abstract class Animal
    {
    public void move()
    {
    System.out.println("moving...") ;
    }
    }

    class Snake extends Animal
    {
    public void move()
    {
    System.out.println("crawling") ;
    }
    }

    class TestAnimal
    {
    static public void main(String args[])
    {
    Animal a1 = new Snake() ;
    Snake s1 = new Snake() ;
    a1.move() ;
    s1.move() ;

    System.out.println(a1.getClass().toString());
    System.out.println(s1.getClass().toString());
    }

    }
    • The answeer is ...
      本文发表在 rolia.net 枫下论坛The object that "a1" points to is an instance of Snake, of Animal, and of Object!
      However, its RUNTIME type is Snake because the Animal "a1" is created according to "the shape of an Snake".
      An object can be of many data types but it have only one Runtime type. This is
      what you get by calling getClass() method.

      If you remove the key word "abstract",
      you will get the same result as you run your testing code.

      IN PRINCILE, we can get rid of the key "abstract" from all the libraries.
      But why people use "abstract"?

      Take Aminal as an example. We know all the
      animals are characteristic of moving. But
      if you told your friends you have bought some animals, your talking sounds funny. Likely,
      as God created anamals, HE did a la model of dove, dog, ...

      If you don't want to use "abstract", you can implement Animal class in the following
      two ways:

      1)
      class Animal
      {
      public void move()
      {
      System.out.println("moving...") ;
      }
      }


      2)
      class Animal
      {
      public void move()
      {
      // no code here
      }

      In either case, you will allow the users of your Animal class to create an ABSTRACT
      ANIMAL. Now I may ask you and your friends
      a question: What animals are your animals?
      I don't think you can answer this question.

      To prevent people from creating ABSTRACT animals, we had better make Animal class abstract. If we stand against this, we may
      get into some dilemma later.

      Interestingly enough, we may also make
      Bird, Snake, Fish, Mammal abstract and
      makde Carp, Parrot, Dog concrete classes.
      However, this will be a design problem.
      You may need to make decisions according
      to how elaborately you will describe the Anaimal kingdom.

      Eseentially, usage of "abstract" is a design
      issue. No absolute right or wrong.


      Hope it helps. Jabber

      In eihter更多精彩文章及讨论,请光临枫下论坛 rolia.net