logo

Wywołanie zwrotne przy użyciu interfejsów w Javie

Wywołanie zwrotne w C/C++: Mechanizm wywoływania funkcji z innej funkcji nazywa się wywołaniem zwrotnym. Adres pamięci funkcji jest reprezentowany jako „wskaźnik funkcji” w językach takich jak C i C++. Zatem wywołanie zwrotne osiąga się poprzez przekazanie wskaźnika funkcji 1() do funkcji 2().
Oddzwanianie w Javie: Ale koncepcja funkcji wywołania zwrotnego nie istnieje w Javie, ponieważ Java nie ma koncepcji wskaźnika. Są jednak sytuacje, w których można mówić o obiekcie wywołania zwrotnego lub interfejsie wywołania zwrotnego. Zamiast przekazywać adres pamięci funkcji przekazywany jest interfejs, który odnosi się do lokalizacji funkcji.
 

Przykład


Weźmy przykład, aby zrozumieć, gdzie można zastosować wywołania zwrotne. Załóżmy, że programista chce zaprojektować kalkulator podatkowy, który oblicza całkowity podatek stanowy. Załóżmy, że istnieją tylko dwa podatki: centralny i stanowy. Podatek centralny jest powszechny, podczas gdy podatek stanowy różni się w zależności od stanu. Całkowity podatek jest sumą obu. Tutaj dla każdego stanu zaimplementowano oddzielną metodę, taką jak stateTax() i wywołaj tę metodę z innej metody CalTax() jako:
 



static void calculateTax(address of stateTax() function) { ct = 1000.0 st = calculate state tax depending on the address total tax = ct+st; }


W powyższym kodzie adres stateTax() jest przekazywany do metody CalcTax(). Metoda CalTax() użyje tego adresu do wywołania metody stateTax() konkretnego stanu i obliczony zostanie podatek stanowy „st”. 
Ponieważ kod metody stateTax() zmienia się z jednego stanu do drugiego, lepiej zadeklarować ją jako metodę abstrakcyjną w interfejsie jako: 
 

pełna forma ide
interface STax { double stateTax(); }


Poniżej znajduje się implementacja stateTax() dla stanu Pendżab: 
 

class Punjab implements STax{ public double stateTax(){ return 3000.0; } }


Poniżej przedstawiono implementację stateTax() dla stanu HP: 
 

class HP implements STax { public double stateTax() { return 1000.0; } }


Teraz metodę CalTax() można zaprojektować jako: 
 

static void calculateTax(STax t) { // calculate central tax double ct = 2000.0; // calculate state tax double st = t.stateTax(); double totaltax = st + ct; // display total tax System.out.println(Total tax =+totaltax); }

Tutaj należy zwrócić uwagę na parametr „STax t” w metodzie obliczTax(). „t” jest referencją do interfejsu „STax”, która jest przekazywana jako parametr do metody. Korzystając z tego odniesienia, metoda stateTax() jest wywoływana w następujący sposób: 
 

double st = t.stateTax();


Tutaj, jeśli „t” odnosi się do metody stateTax() klasy Punjab, wówczas wywoływana jest ta metoda i obliczany jest jej podatek. Podobnie dla klasy HP. W ten sposób przekazując odwołanie do interfejsu do metody obliczTax() możliwe jest wywołanie metody stateTax() dowolnego stanu. To się nazywa mechanizm wywołania zwrotnego.
Przekazując odwołanie do interfejsu, które odwołuje się do metody, możliwe jest wywołanie i użycie tej metody z innej metody.
 

Java
// Java program to demonstrate callback mechanism // using interface is Java // Create interface import java.util.Scanner; interface STax {  double stateTax(); } // Implementation class of Punjab state tax class Punjab implements STax {  public double stateTax()  {  return 3000.0;  } } // Implementation class of Himachal Pradesh state tax class HP implements STax {  public double stateTax()  {  return 1000.0;  } } class TAX {  public static void main(String[] args)  throws ClassNotFoundException IllegalAccessException InstantiationException  {  Scanner sc = new Scanner(System.in);  System.out.println('Enter the state name');  String state = sc.next(); // name of the state  // The state name is then stored in an object c  Class c = Class.forName(state);  // Create the new object of the class whose name is in c  // Stax interface reference is now referencing that new object  STax ref = (STax)c.newInstance();  /*Call the method to calculate total tax  and pass interface reference - this is callback .  Here ref may refer to stateTax() of Punjab or HP classes  depending on the class for which the object is created  in the previous step  */  calculateTax(ref);  }  static void calculateTax(STax t)  {  // calculate central tax  double ct = 2000.0;  // calculate state tax  double st = t.stateTax();  double totaltax = st + ct;  // display total tax  System.out.println('Total tax =' + totaltax);  } } 

Wyjście: 
 

Enter the state name Punjab Total tax = 5000.0


Referencje: 
Jak zaimplementować funkcje wywołania zwrotnego w Javie?  
Core Java: zintegrowane podejście

Utwórz quiz