1// interface in java example
2interface Vehicle
3{
4 public void accelerate();
5}
6class BMW implements Vehicle
7{
8 public void accelerate()
9 {
10 System.out.println("BMW accelerating...");
11 }
12}
13public class InterfaceDemo
14{
15 public static void main(String[] args)
16 {
17 BMW obj = new BMW();
18 obj.accelerate();
19 }
20}
1// Assume we have the simple interface:
2interface Appendable {
3 void append(string content);
4}
5// We can implement it like that:
6class SimplePrinter implements Appendable {
7 public void append(string content) {
8 System.out.println(content);
9 }
10}
11// ... and maybe like that:
12class FileWriter implements Appendable {
13 public void append(string content) {
14 // Appends content into a file
15 }
16}
17// Both classes are Appendable.
1interface methods{
2 public static hey();
3}
4
5class scratch implements methods{
6 // Required to implement all methods declared in an interface
7 // Or else the class becomes abstract
8 public static hey(){
9 System.out.println("Hey");
10 }
11}
1/* File name : MammalInt.java */
2public class MammalInt implements Animal {
3
4 public void eat() {
5 System.out.println("Mammal eats");
6 }
7
8 public void travel() {
9 System.out.println("Mammal travels");
10 }
11
12 public int noOfLegs() {
13 return 0;
14 }
15
16 public static void main(String args[]) {
17 MammalInt m = new MammalInt();
18 m.eat();
19 m.travel();
20 }
21}
1public interface Exampleinterface {
2
3 public void menthod1();
4
5 public int method2();
6
7}
8
9class ExampleInterfaceImpl implements ExampleInterface {
10
11
12 public void method1()
13 {
14 //code here
15 }
16
17 public int method2()
18 {
19 //code here
20 }
21
22}
1class ACMEBicycle implements Bicycle {
2
3 int cadence = 0;
4 int speed = 0;
5 int gear = 1;
6
7 // The compiler will now require that methods
8 // changeCadence, changeGear, speedUp, and applyBrakes
9 // all be implemented. Compilation will fail if those
10 // methods are missing from this class.
11
12 void changeCadence(int newValue) {
13 cadence = newValue;
14 }
15
16 void changeGear(int newValue) {
17 gear = newValue;
18 }
19
20 void speedUp(int increment) {
21 speed = speed + increment;
22 }
23
24 void applyBrakes(int decrement) {
25 speed = speed - decrement;
26 }
27
28 void printStates() {
29 System.out.println("cadence:" +
30 cadence + " speed:" +
31 speed + " gear:" + gear);
32 }
33}
34