context instanceof Activity analysis understanding

instanceof: is a binary operator in Java , which determines whether the object on the left is an instance of the class on the right. If yes, return true; if not, return false.

Example one:

String s = "I AM an Object!"; 
boolean isObject = s instanceof Object; 

eg: We declare a String object reference, pointing to a String object, and then use instanceof to test whether the object it points to is an instance of the Object class. Obviously, this is true, so it returns true, that is, the value of isObject is true.

Example two:

instanceof has some uses.
For example, we wrote a system for processing bills, which has three classes:

public class Bill {
    
    //省略细节} 
public class PhoneBill extends Bill {
    
    //省略细节} 
public class GasBill extends Bill {
    
    //省略细节} 

There is a method in the handler that accepts an object of type Bill and calculates the amount.
Assume that the two bill calculation methods are different, and the incoming Bill object may be any of the two, so instanceof is used to judge:

public double calculate(Bill bill) {
    
     
  if (bill instanceof PhoneBill) {
    
     
  //计算电话账单 
  } 
  if (bill instanceof GasBill) {
    
     
  //计算燃气账单 
  } 
  ... 
  } 

This way you can use one method to handle both subclasses.
However, this approach is often considered to be a failure to take advantage of object-oriented polymorphism.
In fact, the above functional requirements can be completely realized using method overloading. This is the way object-oriented programming should be done to avoid returning to the structured programming mode.
Just provide two methods with the same name and return value, but different parameter types:

public double calculate(PhoneBill bill) {
    
     
  //计算电话账单 
  } 
  public double calculate(GasBill bill) {
    
     
  //计算燃气账单 
  } 

Therefore, using instanceof is not a recommended approach in most cases, and polymorphism should be made good use of.

instanceof is generally used for coercion of object types,
  for example:

 //继承关系 
  class Manager extends Employee {
    
    }

  public void doSomething(Employee e) {
    
     
      if ( e instanceof   Manger){
    
     
        Manager m = (Manager) e ; 
        } 
 } 

Example three:

//判断里面的意思是:context对象是否来自actvity。
if (context instanceof Activity) {
    
      
    Log.i(LOGTAG, "Callback Activity...");  
    Activity callbackActivity = (Activity) context;  
    callbackActivityPackageName = callbackActivity.getPackageName();  
    callbackActivityClassName = callbackActivity.getClass().getName();  
}  

Context in Android may also represent application and service .

Guess you like

Origin blog.csdn.net/zxz_zxz_zxz/article/details/130974418