Tuesday, June 9, 2009

Java Basics Using Qt Jambi Tutorial

Interface

Since we cannot have multiple instances using a class, we can use interfaces. Interfaces can implement from other interfaces.

Ex.

public interface UseCar{

int start (boolean ismoving,boolean key);

int stop (boolean ismoving,boolean breaks);

}

public class BMWCar implements UseCar{ //is used to provide methods declared from the interface.

int start (boolean ismoving, boolean key){

}

}

//is used so it can be available to any package to any classes. If omitted, it can be accessed to classes with same package.


Note: It can also contain constant declarations.


You must remember these rules in using Interfaces:

  1. All the methods in interface should be declared on your source code.

  2. Use public if you want to access the interface to any classes in any package.


When using or to access the interface methods through class instantiation implementing the interface.

Ex.

InterfaceVehicle.java


import java.lang.*;


public class InterfaceVehicle implements UseCar{


public int whichVehicleRunsFaster(int v1, int v2){

if (v1 > v2){

return v1;

}

else{

return v2;

}

}

public static void main(String[] args){

int car1 = 100;

int car2 = 200;

int cars;

InterfaceVehicle vehicle = new InterfaceVehicle();

cars = vehicle.whichVehicleRunsFaster(car1,car2);

System.out.println(cars);

}

}

UseCar.java


import java.lang.*;


public interface UseCar{

public int whichVehicleRunsFaster(int vehicle1, int vehicle2);

}

Note: Classes that implements this interface “inherit” the constants and must implement methods.


If an abstract class contains only abstract method declarations, it should be interface.


to be continued...

No comments: