title: Superclass and Subclass in Java
body: <p>For you, this might be very simple but I have no idea what the difference is.I just want to know the difference between these two codes. Suppose I have some codes as described below. </p>
  
  <p>The first class is Animal which will be the Superclass </p>
  
  <pre><code>public class Animal {
  
      private String name;
      private int weight;
      private String sound;
  
      public void setName(String name){
          this.name = name;
      }
  
      public String getName(){
          return name;
      }
  
      public void setWeight(int weight){
          if(weight &gt; 0){
              this.weight = weight;
          } else {
              System.out.println("Weight must be bigger than 0");
          }
      }
  
      public int getWeight(){
          return weight;
      }
  
      public void setSound(String sound){
          this.sound = sound;
      }
  
      public String getSound(){
          return sound;
      }
  }
  </code></pre>
  
  <p>The second class is Dog which extends the class Animal </p>
  
  <pre><code>public class Dog extends Animal {
  
      public void digHole(){
          System.out.println("Dig a hole");
      }
  
      public Dog(){
          super();
  
          setSound("bark");
      }
  }
  </code></pre>
  
  <p>The last class is the WorkWithAnimals which will print the output </p>
  
  <pre><code>public class WorkWithAnimals {
  
      public static void main(String args[]){
  
          Dog fido = new Dog();
  
          fido.setName("Dadu");
          System.out.println(fido.getName());
  
          fido.digHole();
          fido.setWeight(-1);
      }
  }
  </code></pre>
  
  <p>My question is, what is the difference between Animal fido = new Dog() and Dog fido = new Dog() ?</p>
  
  <p>Since Dog already extends Animal, why do we have to write the code like Animal fido = new Dog() ?</p>
  
  <p>Both of them print the same result, don't they? </p>