Java Tutorial Hub

Training & Tutorials for Java Beginners

Java Tutorial 19 - Interface

 

The following tutorial discusses issues with multiple inheritance and why java does not allow it. It also introduces interfaces

<

Please be patient . Video will load in some time. If you still face issue viewing video click here

 

Syntax for declaring interface

interface <interface_name>{
//methods
}

 

To use a interface in your class , append the keyword “implements” after your class name followed by the interface name

Ex

class Dog implements Pet
 

 

Points to note:

  • The class which implements the interface needs to provide functionality for the methods declared in the interface
  • All methods in an interface are implicitly public and abstract
  • An interface cannot be instantiated
  • An interface reference can point to objects of its implementing classes
  • An interface can extend from one or many interfaces. A class can extend only one class but implement any number of interfaces
       interface RidableAnimal extends Animal, Vehicle

Assignment: To learn interfaces

Step 1) Copy following code into an editor.

interface Pet{
  public void test();
}
class Dog implements Pet{
   public void test(){
     System.out.println("Interface Method Implemented");
  }
   public static void main(String args[]){
     Pet p = new Dog();
     p.test();
  }
}

 

Step 2) Save , Compile & Run the code. Observe the Output.

 

Point to Ponder

While designing ,how do you choose between Abstract & Interface ?


Use an abstract class when a template needs to be defined for a group of subclasses

Use an interface when a role needs to be defined for other classes, regardless of the inheritance tree of these classes

false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4

                                                      Back to Java Tutorials Index Page

 
 
Joomla 1.5 Templates by Joomlashack