At dinner table.
Yash: Today in Java class, we were discussing about
packages. Can you please explain?
Me: Sure. You can consider package as any house in a
neighborhood. Each house has its
residents – humans, animals, and non-living things. If you scale down by one
level, some members of the household have their own rooms while others share
rooms. You can compare those living
house as Java Classes, Interfaces, and/or Enums. Just the way a house may have rooms, a
package may have sub-package – packages in a package.
Yash: I got this. But we were also taking about inheritance.
Me: It is pretty simple.
Yash: How?
Me: Let’s create a scenario.
You have parents – one biological mother and one biological father.
Correct?
Yash: Correct.
Me: Let’s assume me and your mother separate. I decide to marry again. Now you have two
mothers – one biological and the other one will be your Step Mom. It is possible that your step Mom may decide
to separate after a while and I again marry someone else, now you have three
mothers.
Yash: This is complex and crazy and I hope it never happens.
Me: Let’s make it a bit more complex. Your biological mother
may also decide to marry someone else. It is also possible that I and one of
your step moms may decide to have baby.
To make things worse, you may decide to have baby with one of my spouse’s
kid at some point in your life.
Yash: Things may really get ugly here.
Me: Yep. This complexity exists because a baby has two
parents. Now assume, if a baby has only one parent. This type of complexity
cannot arise. It also allows as many babies as possible from a single parent.
Yash: True.
Me: To avoid this complexity, Java does not allow multiple
parents. One parent is allowed.
Yash: Ok. Who is baby
and who is parent in Java?
Me: In Java, class is
the main player. To define relationship of a parent and a baby, we use the
keyword – extends.
Yash: How?
Me: It is
simple.
class B extends A(){
}
Here class A is parent while
class B is baby.
In Java terminology, class A is “super class” while class B
is “sub class”.
Yash: Hmm…. I suppose, if I want to say that class C is sub
class of B then I should write like
class C
extends B(){
}
Me: Fantastic!!!
Yash: And if class D is also a sub class of B then I can
write:
class D
extends B(){
}
Me: Super!!!
Yash: Does it mean we are creating a hierarchy like class A
is super class of class B and classes C & D are sub classes of class B.
Me: Perfect. This whole concept is called inheritance.
Me: Let’s mix packages and inheritance. As it is possible that your grandparents may live
in a different house and I and you live in one house. It is also possible that
classes of same hierarchy belong to different packages. Let’s modify the
picture little bit.
Yash: So it is possible that a class can live in any package
irrespective of the hierarchy.
Me: Yes.
Yash: I have few more questions.
Me: I think, this is good enough for today.
Yash: Okay! Good night.
No comments:
Post a Comment