简体   繁体   中英

Changing the reference object in java

I got these code that have confused me from tutorialspoint.com

class Animal{

  public void move(){
  System.out.println("Animals can move");
  }
}

class Dog extends Animal{

   public void move(){
       System.out.println("Dogs can walk and run");
   }
    public void bark(){
      System.out.println("Dogs can bark");
   }
}

 public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal b has reference an object of  type animal class
      Animal b = new Dog(); // Animal reference but Dog object how??

      a.move();// runs the method in Animal class
      b.move();//Runs the method in Dog class
      b.bark();
   }
 }

Animal reference to dog object is working ..I dont understand why is that working .Need to know the underlying concept behind it. Also if Animal reference to dog object is possible why not Dog reference to Animal not possible? like:

public class TestDog{

   public static void main(String args[]){
      Animal a = new Dog(); // Animal b has reference an object of  type animal class
      Dog b = new Animal(); //now this leads to an error

      a.move();
      b.move();

   }
 }

It shows error during compilation

Inheritance is the main concept behind it. Read about it anywhere and you will get the idea.

Generally, the case in the last code snippet is: every dog is an animal, but not every animal is a dog. Just like in real life.

As you can see the class Dog extends Animal . What this means is, that Dog has all attributes and methods animal has. You could also have a class Cat which extends Animal . So in practice you won't have to write the same code over and over again, if you have a bunch of similar classes.

You get the compilation error because Animal has for example no idea what bark() does, while Dog knows about all methods/attributes in Animal. As already mentioned "every dog is an animal, but not every animal is a dog".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM