Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Interface

Status
Not open for further replies.

pottys

Programmer
Mar 8, 2008
1
IN
i have creared a new interface.how can i use it in my programs.where should i place the interface to reuse it.
 
Program by example.
Code:
public interface Sellable{
  public double getPrice();
}

public class Car implements Sellable{
  public Car(double price){
    this.price=price;
   }

 public double getPrice(){ return price; }
 }

The interface should be available in the classpath of the case to use it.
 
->how can i use it in my programs?
You can use it the way obadare shown except for the following points :
- In Java, a source file can only contain one public class or interface.
- The field to store the car price has been forgotten.

Corrected, odabare code gives :
File "Sellable.java"
Code:
public interface Sellable{
  public double getPrice();
}

File "Car.java" (given code assumes that both java files are in same folder/package and "package" instructions are missing. See other answer for more details)
Code:
public class Car implements Sellable{
  [COLOR=red]private double price = -1;[/color]

  public Car(double price){
    this.price=price;
   }

  public double getPrice(){ 
    return price; 
  }
}

->where should i place the interface to reuse it?
You can place your interface everywhere you want since you import it after in the class that implements it.
Example :
-If your Interface is located in the "org/tekTips/interfaces" folder in your project's sources, java will consider it belongs to "org.tekTips.interfaces" package.
-If your Class is located in the "org/tekTips/classes" folder in your project's sources, java will consider it belongs to "org.tekTips.classes" package.

Soo, to use the interface, you must use the "import" keyword to give Java the path to reach your interface.
With "package" and "import" instruction added, the code is now :
File "Sellable.java" (in "org/tekTips/interfaces" folder in your project's sources)
Code:
[COLOR=red]package org.tekTips.interfaces;[/color]
public interface Sellable{
  public double getPrice();
}

File "Car.java" ((in "org/tekTips/classes" folder in your project's sources)
Code:
[COLOR=red]package org.tekTips.interfaces;
import org.tekTips.interfaces.Sellable;
[/color]
public class Car implements Sellable{
  [COLOR=red]private double price = -1;[/color]

  public Car(double price){
    this.price=price;
   }

  public double getPrice(){ 
    return price; 
  }
}


Water is not bad as long as it remains outside human body ;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top