接口内部的类实现了相同的接口,我们通过这种方式实现了什么?我的问题:文本观察者.java:无复制跨度.java:

2022-09-01 23:49:00

我的问题:

我正在查看TextWatcher的源代码,但我在这里没有得到这个概念。扩展到NoCopySpan有什么意义?

文本观察者.java:

public interface TextWatcher extends NoCopySpan {
     public void beforeTextChanged(CharSequence s, int start, int count, int after);
     public void onTextChanged(CharSequence s, int start, int before, int count);
     public void afterTextChanged(Editable s);
}

无复制跨度.java:

package android.text;

/**
 * This interface should be added to a span object that should not be copied into a new Spanned when performing a slice or copy operation on the original Spanned it was placed in.
 */
public interface NoCopySpan {
    /**
     * Convenience equivalent for when you would just want a new Object() for
     * a span but want it to be no-copy.  Use this instead.
     */
    public class Concrete implements NoCopySpan {}
}

答案 1

NoCopySpan只是一个标记界面。根据javadoc,它用于修改对象复制例程的行为(它依赖于组件的类型)。例如,android.text.SpannableStringBuilder使用这样的继承信息来跳过构造时的跨度复制。Spanned

这种方法有一些缺点,但仍然很常见。类存在的原因是提供方便的方法来构建接口的op-opdummy(或默认)实现。ConcreteNoCopySpan


答案 2

至于接口的规范,实现相同接口的内部类可以用作接口在外部任何地方的默认实现/表示NoCopyScan

接口中的内部类隐式被视为静态内部类。我们可以像静态内部类一样实例化接口的内部类并投入使用。请在下面的内部类的帮助下找到一个简单的示例,描述接口的默认实现的用法:NoCopyScan

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
interface NoCopy{

public void doStuff();

public class Conc {             //Inner Class
    public int retStuff(){
        return 2;
    }
    }




//  public void doStuff(){
//      System.out.println("Overriding in inner class");
//  }
}


 class ConcOut {

    public int returnStuff(){
        return 5;
    }


    public void doStuff(){
        NoCopy.Conc innerObj = new NoCopy.Conc();    //Instantiating inner class
        //NoCopy.Conc innerObj = (new ConcOut()).new Conc();

        System.out.println("overriding in outside class ConcOut "+ innerObj.retStuff());                              // calling the method of inner class
    }
}

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        ConcOut conObj = new ConcOut();
        conObj.doStuff();
        //ConcOut.Conc concInner = conObj.new Conc();

    }
}

推荐