·  JAVA – Syntax – Terms – Inheritance

 

- Info:

  - Inheritance is the capability of class to use the properties & methods of another class while adding its own functionality.

  - In Java this is done through the use of extends keyword.

  - extends keyword allows class to extend another class, therefore inheriting its properties and methods (inheritance):

    class Bird extends Animal

  - You can extend only from one class since multiple inheritance is not supported (unlike C++).

  - Single extend can be combined with implementing multiple interfaces:

    class Bird extends Animal implements interface1, interface2

 

- Example:

  - In this example class Bird extends class Animal since Animal contains 'name' and 'eat()' common to all animals.

  - Bird class adds 'wingsSpan' and 'fly()' which is characteristic only for Birds.

  - In this example Bird constructor expects two parameters: name and wings span.

  - Name is forwarded to Animal constructor by using keyword super, which must be first line in Bird constructor.

  - If there is no default constructor Animal() then parent constructor must be explicitly calles as in this example.

  - Create JAVA Console Application Test.java

 

    Test.java

    public class Test{ 

      public static void main(String[] args) {  

        Bird swan = new Bird("swan", 10);  //Create object calling constructor with two parameters.

             swan.fly();              

      }

    }

 

    class Animal {

      String name;

      void   eat   ()            { System.out.println(name + "is eating."); };

      public Animal(String name) { this.name = name; } //'this' is used to distinguish 'name' variables.

    } 

      

    class Bird extends Animal {

      int    wingsSpan;

      void   fly   ()            { System.out.println(name + "is flying."); };

      public Bird(String name, int span)  {   

        super(name);      //Parent constructor call must be the first statement in a constructor.

        wingsSpan = span;

      }

    }