In a nutshell, how and why is this possible:
Object obj=new MyClass();
Object is the superclass of all objects, therefore MyClass is a child class of Object. In general, in Java, Why is it possible to use the constructor of a child class in the parent class?
I understand how it could go the other way around, since the child has all the variables/methods of the parent class, so when you initialize them you are just initializing the variables specified in the parent constructor, that exist by definition in the child. The problem is, when you go the other way around, it is not necessarily true. A child can have variables the parent doesn't, so how is it possible to use the child constructor with the parent, when the parent does not even have the variables in the first place?
What uses does this feature have in development? I would think that if you want an instance of class B, you would declare it as B thing=new B(), and not A thing=new B(). This is probably my inexperience talking, so I would appreciate enlightenment on why and how a parent class can be initialized as one of its children.
First, you must get a clear understanding of things. Your example expression:
Object obj = new MyClass();
is actually a compound of two elementary operations.The first one is creating an instance of MyClass:
new MyClass()
. Thenew
keyword is basically the only way of actually obtaining an instance of a class (lets ignore runtime reflection to keep this simple), and you are literally naming what you want to create (MyClass) here by its constructor. There is no way to create anything other than what you literally named with the new keyword. The result of new is (implicitly) an instance of MyClass, but the explicit result of anew X
is a reference of typeX
(the reference referring to the newly created instance).Now the second operation is assigning the reference to your (new) MyObject to another reference of type Object. And this is valid because MyObject is an Object (due to inheritance).
Why would you need this?
This is an essential feature to actually make use of polymorphism. The ability to refer to any child class as its superclass is what makes polymorphism so powerful. You basically will use it everywhere where there is an aspect common to two classes, but there are also differences.
A real world example would be graphical user interfaces. There are buttons, lists, tables and panels in a window, which are all user interface elements, but each does a different thing. To present them neatly organized in a window, these elements are often nested into panels, more abstractly said into containers. Now a container doesn't care what kind of elements go into it, as long as they are components. But to handle them properly a container does need some basic information about these components, mostly how much space they occupy and how to actually draw them. So this is modelled as something like:
Thats almost straight lifted out of the JDK, the point is, if you needed to refer to each Component as its concrete type, it would be impractical to build a Container, it would need extra code for each Component you decide to make (e.g. there would be an addButton, addTable and so on). So instead, Container just works with reference to Component. No matter what Component is created (e.g. Button, CheckBox, RadioButton etc.), since Container just relies on them to all be Component's, it can handle them.
You are thinking in terms of C++ semantics, but this is Java. In Java, all non-primitive type variables are references, not instances.
In C++, when you say
you allocate a new
Object
instance on stack or in static memory.When you say
you invoke a constructor of
Object
class that takesMyObject
pointer (or may be something else that MyObject can be converted to).In Java,
does not create any instances of
Object
. It simply creates a variable that can have a reference to anObject
instance, but at the moment does not refer to any. It is initialized tonull
.allocates an instance of
MyObject
. It does not allocate a new instance ofObject
. It simply sets the variable to refer to the new instance. In C++ terms this is much more similar toSo we're not constructing a parent instance from child instance. We're changing a value the variable is set to, from null to a new child instance.
This is not correct. When you do
Object obj;
declares a reference of the typeObject
andnew MyClass();
returns a reference to the object it created.So, you are instantiating a
MyClass
and assigning the reference to the object created to a reference of the typeObject
, and this is possible becauseMyClass
is anObject
.As you say,
That's called extending the parent functionality (inheritance).
For your second question think about the classic
Animal
example: Suppose you create aAnimal
class and you create a methodmakeSound()
on it.Now you create two subclasses of
Animal
,Dog
andCat
, that overrides themakeSound()
method ofAnimal
(aDog
barks and aCat
meows).Imagine that you represent a room full of
Animal
s (Dog
s andCat
s) using aList
, and you want to make all of themmakeSound()
. Your list will be declared asList<Animal>
because you don't know the kind ofAnimal
s that you will store.And then you iterate over the
List
to callmakeSound()
for eachAnimal
. It doesn't matter if theAnimal
is aDog
or aCat
, it will make it's sound.And then imagine you want to add
Bird
s to theList
. Easy, isn't it?Every class in Java is descended from
Object
. SoMyClass
is anObject
, by definition, but a more specialized version of it. Think of it like this: every living creature is anAnimal
. ACat
is a special kind of animal; a specific type. Since theCat
is anAnimal
, you can still just call it anAnimal
:But doing so, with
a
, you can't do anything specific to aCat
, likemeow()
orpurr()
, but you can call methods which are valid for allAnimal
s, such asbreathe()
.HTH
Because a
MyClass
is aObject
. Note that java is special becauseObject
is the superclass of every other class type (there is no equivalent in C++).A more interesting example would be if you had a class or interface and one or more subclasses. This comes up all the time in OOD. Consider for example java's jdbc API: a common set of interfaces to connect and query a database that can be implemented by different concrete classes. You only need to code to the API and then at runtime use the implementation for your DB of choice.