[英]Method declaration and defining in java
關於我的疑問,我需要一些建議。 我需要在一個類/文件中聲明一個函數,然后在另一個類中定義它,是否可以這樣做?
我的實例是我有一個集成到我的應用程序中的計費模塊。 我只是從其他模塊接受此模塊的一些參數,並在計費模塊中聲明和定義的函數中對其進行處理。 當我將此計費模塊合並到所有其他模塊時,我需要在每個模塊中運行一些代碼集,這對於每個模塊都是唯一的。 因此,請提出一種在計費模塊中聲明函數的方法,該函數可以在所有其他模塊中定義,並且應該在計費模塊中可執行。
聽起來您應該創建一個聲明方法的接口,然后擁有要實現該接口的任何類。
在計費模塊中
public interface SomeInterface
{
public void someMethod (...);
}
在其他模塊中:
public class SomeClass1 implements SomeInterface
{
public void someMethod (...)
{
....
}
}
public class SomeClass2 implements SomeInterface
{
public void someMethod (...)
{
....
}
}
現在,如果您的計費模塊具有對其他模塊類對象的引用,則可以為每個模塊調用someMethod (...)
。
這就是接口的用途。
我們可以創建接口來編寫方法聲明,然后可以實現該接口。無論何時實現接口,都需要覆蓋實現類中接口中的所有方法。
例如:語法
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
//這是一個接口
interface Animal {
public void eat();
public void travel();
}
//class is implementing the interface
public class MammalInt implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
}
這是您想要實現的!! 計費模塊:定義一個接受一些參數進行處理的接口。 在計費模塊中的某處實現此接口。 在其他模塊中:接受計費模塊接口對象,然后調用該函數來處理提供的參數。
BILLING MODULE:
public interface myinterface{
public void process(Object parameter1);
}
public class myinterfaceImpl implements myinterface{
public void process(Object parameter1){
// process parameter1
}
}
Other Modules
myMethod(myinterface myinterfaceObj){
myinterfaceObj.process(Object myparam1)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.