program tip

재정의 할 때 super () 메서드를 호출하지 않아야 할 때?

radiobox 2020. 8. 4. 07:36
반응형

재정의 할 때 super () 메서드를 호출하지 않아야 할 때?


내 자신의 Android 사용자 정의 클래스를 만들 때 extend기본 클래스입니다. 나는 기본 메서드를 재정의 할 때 다음, 나는 항상 전화 super()난 항상에서 할 것처럼, 방법 onCreate, onStop

그리고 처음부터 Android 팀이 super모든 메소드 재정의 를 항상 호출하도록 권고 했으므로 이것이 사실이라고 생각했습니다 .

그러나 많은 책에서 나보다 경험이 많은 개발자가 종종 전화를 생략 super하고 지식이 부족하다고 생각합니다. 예를 들어,이 기본 보면 SAX의 파서 클래스 super생략 startElement, charactersendElement:

public class SAXParser extends DefaultHandler{
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if(qName.equalsIgnoreCase("XXY")) {
            //do something
        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        //do something
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {
        if(qName.equalsIgnoreCase("XXY")) {
            //do something
        }else () {
            //do something
        }
    }
}

Eclipse 또는 다른 IDE를 통해 대체 메소드를 작성하려고 super하면 항상 자동화 된 프로세스의 일부로 작성됩니다.

이것은 단순한 예일뿐입니다. 책은 비슷한 코드가득합니다 .

언제 전화해야하는지, 언제 전화 super를 생략 할 수 있는지 어떻게 알 수 있습니까?

추신. 이 특정 예에 구속하지 마십시오. 그것은 많은 예에서 무작위로 선택된 예일뿐입니다.

(이것은 초보자 질문처럼 들릴 수 있지만 정말 혼란 스럽습니다.)


super메서드 를 호출하면 메서드 의 동작을 재정의 하는 것이 아니라 확장 하는 것입니다.

에 대한 호출 super은 확장하는 클래스가 해당 메소드에 대해 정의한 모든 논리를 수행합니다. super메소드 재정의에서 구현 을 호출하는 순간 중요 할 수 있음을 고려 하십시오. 예를 들어 :

public class A { 
    public void save() { 
         // Perform save logic
    }
}

public class B extends A {
    private Object b;
    @Override
    public void save() { 
        super.save(); // Performs the save logic for A
        save(b); // Perform additional save logic
    }
}

에 대한 호출 은이 순서대로 B.save()save()논리를 수행합니다 . inside 전화하지 않았다면 호출 되지 않습니다. 당신이라고한다면 , 효과적으로 이후에 수행 될 것이다 .ABsuper.save()B.save()A.save()super.save()save(b)A.save()B.save()

의 동작 재정의 하려면 super(즉, 구현을 완전히 무시하고 모든 것을 직접 제공하려는 경우) 호출하면 안됩니다 super.

In the SAXParser example you provide, the implementations of DefaultHandler for those methods are just empty, so that subclasses can override them and provide a behavior for those methods. In the javadoc for this method this is also pointed out.

public void startElement (String uri, String localName,
    String qName, Attributes attributes) throws SAXException {
    // no op
}

About the super() default call in code generated by IDEs, as @barsju pointed out in his comment, in each constructor there's an implicit call to super() (even if you don't write it in your code), which means, in that context, a call to super's default constructor. The IDE just writes it down for you, but it would also get called if you removed it. Also notice that when implementing constructors, super() or any of its variants with arguments (i.e. super(x,y,z)) can only be called at the very beginning of the method.


How do they know when you must call super and when you can omit it calling?

Usually, if a special API method has a critical meaning to the underlying framework context life cycle, it will always be explicitly stated and highlighted in the API documentation, like the Activity.onCreate() API documentation. Moreover, if the API follows a robust design, it should throw some exceptions to alert the consumer developer at project compile time, and make sure it will not generate a fault at run time.

If this is not explicitly stated in the API documentation, then it is quite safe for the consumer developer to assume the API method is not mandatory to call when overriding it. It is up to the consumer developer to decide whether to use the default behavior (call the super method) or completely override it.

If the condition is permitted (I love open-source software), the consumer developer can always check out the API source code and see how the method is actually written under the hood. Check out Activity.onCreate() source and DefaultHandler.startElement() source for example.


The test you should do in your head is:

"Do I want all of the functionality of this method done for me, and then do something afterwards?" If yes, then you want to call super(), and then finish your method. This will be true for "important" methods such as onDraw(), which handles lots of things in the background.

If you only want some of the functionality (as with most methods that you will override) then you probably don't want to call super().


Well Xavi gave a better answer.. but you probably might be knowing what does super() do when called in a overridden method... it ads what have you done with the default behaviour..

e.g:

onDraw() 

method in view class when overridden.. you draw something before saying super.onDraw() it appears once the view is fully drawn.. so here calling super is necessary since android has some critically important things to do (like onCreate())

but at the same time

onLongClick()

when you override this you don't want to call super because it brings up a dialog with list of options for a EditText or any other similar view.. Thats the basic diff.. you have choice to leave it some times.. but for other methods like onCreate() , onStop() you should let the OS handle it..


I didn't get your question clearly, but if you are asking about why not calling the super method:

There is a reason for calling the super method: if there is no zero argument constructor in the parent class then it is not possible to make a child class for that, so either you need to keep a no argument constructor in the parent class or you need to define super() calling statement with argument(how much argument constructor you have used in super class) at the top of the child class constructor.

I hope this helps. If not, let me know.


I implemented a constraint array list like

public class ConstraintArrayList<T> extends ArrayList<T> {
  ConstraintArrayList(Constraint<T> cons) {this.cons = cons;}
  @Override
  public boolean add(T element) {
    if (cons.accept(element))
      return super.add(element);
    return false;
  }
}

If you look at the code, it simply does some pre-checking before actually letting the super class perform the actual addition of element to the list. This tells one of the two fold reasons for method overriding:

  1. Extensibility where you want to extend what the super class can do
  2. Specificity where you want to add specific behaviour through polymorphism such as in the common Animal kingdom example of move semantics where the way birds move (fly) and frogs move (hop) are specific to each sub class.

For those who also wondered which overridden methods from Android Framework should call super and found this question - here's a current hint from 2019 - Android Studio 3+ will tell you when you need it.

enter image description here

참고URL : https://stackoverflow.com/questions/10244785/when-not-to-call-super-method-when-overriding

반응형