MORTAL KOMBAT!!!
Goblin goblin =
new
Goblin();
Golem golem =
new
Golem();
while
(goblin.
health
>
0
&& golem.
health
>
0
) {
goblin.attack(golem);
golem.attack(goblin);
}
Honorably, these two will fight until either of their
health
values reaches or
falls below 0.
Do note that child classes can add new methods of their own; they don’t
only have to modify the parent’s methods; they can add entirely new suites
of functionality.
Real world examples
I’m a bit biased as an Android developer, but I think these are some relevant
examples.
One part of a screen in Android is a
Fragment
. We can extend
Fragment to create one of our own, maybe a ListFragment, and wire
that user interface up to our list of reasons to hate ourselves.
The entire screen itself is often an
Activity
. We can extend
Activity, maybe with a MainActivity, to start adding our own
fragments to the app, using the parent Activity’s methods!
An input field that the user can edit, an
EditText
, extends from a
TextView
, which just displays text. An EditText can do everything
a TextView can and more …mostly editing that text.
We can create a database on our Android device by extending the
RoomDatabase
class. No need to embarrass ourselves trying to
write a local database from scratch, we just have to inherit from this
class then follow the rules.
That last example? Look at
how much code your special database class
automatically has
, just from inheriting it. Hell yeah! Inheritance!
There’s a lot more to uncover here with inheritance honestly. Want to learn
more about it from me? We’re gonna need a bigger book.
Polymorphism
Probably the biggest and scariest word for people learning Java. And
honestly, I would not be surprised if a lot of people that program in Java full
time don’t even know what it means.
And that’s not a knock against them. It’s both a tricky concept and a
confusing word. Okay, maybe slightly a knock against them.
But not you. You will know. I will force you to learn... if you voluntarily
read.
What is polymorphism?
Java is smart sometimes. One thing it’s smart at is knowing which method
to call.
It probably sounds easy. I have a class, and it has a method. I create an
instance of that class, and call that method. How could a programming
language get confused?
When inheritance is involved, that’s when.
Let’s harken back to our Monster example. We wrote some code that looked
like this:
Goblin warts =
Do'stlaringiz bilan baham: |