MrSparkly
18
Q:

java define interface

// interface in java example
interface Vehicle
{
   public void accelerate();
}
class BMW implements Vehicle
{
   public void accelerate()
   {
      System.out.println("BMW accelerating...");
   }
}
public class InterfaceDemo
{
   public static void main(String[] args)
   {
      BMW obj = new BMW();
      obj.accelerate();
   }
}
4
Interfaces specify what a class must do and not how. 
  It is the blueprint of the class.It is used to achieve total abstraction. 
    Interfaces are used to implement abstraction

Let’s consider the example of vehicles like bicycle, car, bike………, 
they have common functionalities. So we make an interface and put all these
  common functionalities. And lets Bicycle, Bike, car ….etc implement
  all these functionalities in their own class in their own way.
1
// interface syntax
interface InterfaceName
{
   fields // by default interface fields are public, static final
   methods // by default interface methods are abstract, public
}
1
/* File name : MammalInt.java */
public class MammalInt implements Animal {

   public void eat() {
      System.out.println("Mammal eats");
   }

   public void travel() {
      System.out.println("Mammal travels");
   } 

   public int noOfLegs() {
      return 0;
   }

   public static void main(String args[]) {
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
} 
3
/* File name : Animal.java */
interface Animal {
   public void eat();
   public void travel();
}
2
// Assume we have the simple interface:
interface Appendable {
	void append(string content);
}
// We can implement it like that:
class SimplePrinter implements Appendable {
 	public void append(string content) {
   		System.out.println(content); 
    }
}
// ... and maybe like that:
class FileWriter implements Appendable {
 	public void append(string content) {
   		// Appends content into a file 
    }
}
// Both classes are Appendable.
0
how to implement a interface in java
0

New to Communities?

Join the community