Last active
January 4, 2016 07:31
-
-
Save deepak/5fe96a9a70d2693b8df3 to your computer and use it in GitHub Desktop.
calling different methods in sub-class (ruby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Foo { | |
public String ping() { | |
return "ping"; | |
} | |
public String pong() { | |
return "pong"; | |
} | |
} | |
public class BadFoo extends Foo { | |
public String ping() { | |
return super.pong(); | |
} | |
public String pong() { | |
return super.ping(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
def ping | |
"ping" | |
end | |
def pong | |
"pong" | |
end | |
end | |
# does not work in ruby | |
# but `super.method_name` works in java | |
# how to do this in ruby ? | |
class BadFoo < Foo | |
def ping | |
super.pong | |
end | |
def pong | |
super.ping | |
end | |
end | |
# thanks to Yuva | |
class ConfusedFoo < Foo | |
alias_method :parent_pong, :pong | |
alias_method :parent_ping, :ping | |
def ping | |
parent_pong | |
end | |
def pong | |
parent_ping | |
end | |
end | |
# Java's way of doing things is verbose | |
# but it does make this usecase easier | |
# but not the most common one. ie. calling the super method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment