Java - Overloading and Overriding -
01 class subclass extends superclass {} 02 class appsuperclass { 03 /** 04 * @param superclass 05 */ 06 public void print(superclass superclass) { 07 system.out.println("appsuperclass:superclass parameter"); 08 09 } 10 /** 11 * @param subclass 12 */ 13 public void print(subclass subclass) { 14 system.out.println("appsuperclass:subclass parameter"); 15 16 } 17 } 18 19 class appsubclass extends appsuperclass { 20 /** 21 * @param superclass 22 */ 23 public void print(superclass superclass) { 24 system.out.println("appsubclass:superclass parameter"); 25 26 } 27 /** 28 * @param subclass 29 */ 30 public void print(subclass subclass) { 31 system.out.println("appsubclass:subclass parameter"); 32 33 } 34 } 35 public class overloadedtest { 36 public static void main(string[] args) { 37 appsuperclass appsuperclass = new appsuperclass(); 38 appsuperclass appsubclass = new appsubclass(); 39 superclass superclass = new superclass(); 40 superclass subclassinstance = new subclass(); 41 /* 42 * making request print appsuperclass 43 * 1. passing superclass instance 44 * 2. passing subclass instance (*make note of type) <img src="http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif?m=1304052800g" alt=":)" class="wp-smiley"> 45 */ 46 47 appsuperclass.print(superclass); 48 appsuperclass.print(subclassinstance); 49 /* 50 * above repeated appsubclass instance 51 */ 52 appsubclass.print(superclass); 53 appsubclass.print(subclassinstance); 54 } 55 56 }
when run
appsuperclass:superclass parameter appsuperclass:superclass parameter appsubclass:superclass parameter appsubclass:superclass parameter
how can
appsuperclass:superclass parameter appsuperclass:subclass parameter appsubclass:superclass parameter appsubclass:subclass parameter
as o/p without changing type of of objects?
your question isn't clear, sounds you're after execution-time overloading, doesn't exist in java. overloads entirely resolved @ compile-time. 1 option this:
public void print(superclass superclass) { if (superclass instanceof subclass) {] print((subclass) superclass); return; } system.out.println("appsuperclass:superclass parameter"); }
note you'd need in override well, or have template method this, , separate printimpl(superclass)
method can overridden in subclass.
to take logical extreme, might have:
class appsuperclass { public final void print(superclass superclass) { if (superclass subclass) { printimpl((subclass) superclass); } else { printimpl(superclass); } } protected void printimpl(superclass superclass) { ... } protected void printimpl(subclass subclass) { ... } }
appsubclass
override printimpl
(one or both overloads).
edit: noted in comments, alternative use visitor pattern. it's not pattern i'm terribly fond of, if can modify superclass
, subclass
know appsuperclass
(or interface implements) work you.
Comments
Post a Comment