inheritance - What happens when a method is overridden in Java? -


when predefined method in java overridden...

  1. only method signature must same
  2. both method signature , inheritance must same

what answer? 1 or 2

i know when override method in superclass, method signature should same. inheritance? have read question in book, did not find answer after research.

from docs:

an instance method in subclass same signature (name, plus number , type of parameters) , return type instance method in superclass overrides superclass's method.

the method signature must same; is, name, parameters, position of parameters, , number of parameters must match.

the common example of tostring(), lives on object. object's tostring method defined this:

public string tostring() {     return getclass().getname() + "@" + integer.tohexstring(hashcode()); } 

...whereas abstractcollection*'s tostring method defined this:

public string tostring() {     iterator<e> = iterator();     if (! it.hasnext())         return "[]";      stringbuilder sb = new stringbuilder();     sb.append('[');     (;;) {         e e = it.next();         sb.append(e == ? "(this collection)" : e);         if (! it.hasnext())             return sb.append(']').tostring();         sb.append(',').append(' ');     } } 

notice both of method signatures same, return different. intention of overriding; parent class has defined specific behavior doesn't make sense in children classes, 1 overtakes behavior , makes suitable child class.

*: used abstractcollection, arraylist , linkedlist.


to expand bit: visibility of method in child plays role.

from handy chart, methods have private modifier cannot passed subclasses.

when overriding methods, cannot reduce visibility of method; is, cannot descend lower in visibility order provided.

to help, here's quick list.

if method in parent is...

  • public: subclass' override must public.
  • protected: subclass' override can either public or protected.
  • <no modifier> or package-private: subclass' override can public, protected, or package-private.
  • private: subclass doesn't know method exists.

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -