inheritance - What happens when a method is overridden in Java? -
when predefined method in java overridden...
- only method signature must same
- 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.
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 mustpublic
.protected
: subclass' override can eitherpublic
orprotected
.<no modifier>
or package-private: subclass' override canpublic
,protected
, or package-private.private
: subclass doesn't know method exists.
Comments
Post a Comment