Hi Smriti,
I agree with you that no objects will be created, if what you have asked is as entered in the Khalid book. In fact, it should give a compile error.
I do not agree with John, who has mentioned that the following code will compile -
pitBull = new Mammal();
This code cannot compile.
Mammal is the superclass of Dog, so you can write it as
Mammal pitbull = new Dog();//upcasting Dog object to its superclass.
but you can't write -
Dog pitBull = new Mammal(); // downcasting is not allowed
The basic thing to remember is that, you can upcast an object, you cannot downcast it.
The Object class is the superclass of all classes. All classes are subclasses or the class Object. If you define a class which does not extend any other class, such as-
class MyClass {}
Here, though we are not using the
extendskeyword to inherit a class,
Java implicitly extends the class MyClass with the class Object.
Now, when we write, Object c = new MyClass();
it is correct, but is incorrect to write -
MyClass c = new Object();
Smriti, could you try posting this question in the Mock Errata section and see what other people have to say about it.
I hope that helps.
Niraj