Creating and Using Interfaces
Here is an example interface that we can use with the 3
subclasses of the Animal class discussed in the last 3 lessons.
public interface working
{
public void work();
}
Multiple inheritance is not allowed in java, but as an
alternative
the programmer can use interfaces. An interface looks like a class
except that all it's methods are abstract and any data fields
declared must be static final. Any class using an interface must
include the word implements followed by the interface name in its class
declaration. The user must include code in it's class for all methods that it is
implementing from the interface.
Abstract classes and interfaces are similar. Neither can
instantiate
a concrete object. All methods in am interface must be abstract.
Abstract classes can contain concrete methods. A class can
inherit from only one superclass but it can implement from
multiple interfaces.
Example using the interface above within the structure
shown in
the Animal and Dog classes.
public class workingDog extends Dog implements working
{
public workingDog(String gg)
{
super(gg);
}
public void work();
{
speak();
System.out.println("dpg
barking");
}
}
************************************************
public class demo
{
public static void main(String[] args)
{
workingDog mydog = new
workingDog("Waldo");
mydog.work();
}
}