简体   繁体   English

如何更改Java类的predifine方法

[英]How to change in predifine method of java class

I want to change in predefined method of ArrayList class. 我想更改ArrayList类的预定义方法。 suppose if we add any element to arraylist . 假设是否将任何元素添加到arraylist。 simultaneously system will print "value is added in arraylist" . 同时系统将显示“在arraylist中添加了值”。 is it possible to do changes on add() of ArrayList class. 是否可以对ArrayList类的add()进行更改。

In this situation composition is usually preferred over inheritance (see http://en.wikipedia.org/wiki/Composition_over_inheritance ). 在这种情况下,通常优先选择组合而不是继承(请参阅http://en.wikipedia.org/wiki/Composition_over_inheritance )。

For example, if you follow the approach of extending the ArrayList class, do you also want your logic invoked when add(int index, E element) is called. 例如,如果您遵循扩展ArrayList类的方法,是否还希望在调用add(int index, E element)时调用逻辑。 What about addAll(Collection<? extends E> c) . 那么addAll(Collection<? extends E> c) What if a new add method is added in a subsequent version of Java? 如果在Java的后续版本中添加了新的add方法怎么办?

Instead, consider implementing your own List . 相反,请考虑实现自己的List Internally it would delegated operations to an ArrayList , but you are forced to think about how to handle each type of addition. 在内部,它将操作委派给ArrayList ,但是您不得不考虑如何处理每种类型的加法。

public class foo extends ArrayList<Object> {
  @Override
  public boolean add(Object e) {
    // print your stuff here
    return super.add(e);
  }
}

Are you asking about method overriding ?? 您是否在询问方法overriding

public class MyArrayLIst  extends ArrayList<ClassObj>{

   @Override
   public void add(ClassObj obj) {
      //sysout
      return super.add(obj);

   }


}

make your own overridden add method which calls add method of ArrayList and prints what you want as well. 制作自己的重写的add方法,该方法调用ArrayList的add方法并同时打印您想要的内容。 must be done with inheriting the class. 必须通过继承该类来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM