Reputation: 197
So I understand that due to polymorphism one is allowed to do: Superclass Apt = new Subclass(); But I was wondering in the case of:
Superclass Abc = new Subclass();
do(Abc);
void doThat(Superclass Abc)
Abc.Ball();
So in the Abc.method call inside the method doThat, does this make a call to the Ball method of the Superclass or does it make a call to the Ball method of the Subclass (assuming that the subclass has overridden the Ball method). If it does make a call to the overridden Ball method of the Subclass, why can we just not make the method doThat be: void doThat(Subclass Abc) instead. Thanks for the help and I'll clarify more if it doesn't make sense.
Upvotes: 1
Views: 203
Reputation: 9049
does this make a call to the Ball method of the Superclass or does it make a call to the Ball method of the Subclass
The call Abc.Ball()
will call the overriden method in the subclass.
If it does make a call to the overridden Ball method of the Subclass, why can we just not make the method doThat be: void doThat(Subclass Abc) instead
Imagine you have two subclasses of Superclass
:
Superclass abc = new SubclassA();
Superclass xyz = new SubclassZ();
Defining void doThat(Superclass abc)
means that the method doThat()
will accept any object that is an instance of Superclass
or any of its subclasses. Then you could do doThat(abc)
and doThat(xyz)
and both would call the Ball()
method in the appropriate instances.
In contrast, if you had doThat(SubclassA abc)
, you would also need a specific method for each subclass of Superclass
, like doThat(SubclassZ xyz)
.
Upvotes: 1
Reputation: 2887
It's calling the overridden method that's the method overriding is for.
void doThat(Subclass Abc)
if you use Subclass
here you can only pass Subclass instance to this. Instead if you have
void doThat(Superclass Abc)
Then you can pass any object which implements Superclass
That's where the polymorphism comes. doThat
method accepts many type of objects, only requirement is it should implerments Superclass.
If I explained further,
Lets say you have two Subclass called, Subclass1
and Subclass2
and these are implementation of Superclass where the Superclass is an interface. (These Subclasses should implements Superclass method definitions, therefore both subclasses has ball
method)
Then whatever the instance come to the doThat
method it calls the ball
method of the corresponding object. As the void doThat(Superclass Abc)
accept Superclass type.
Upvotes: 2
Reputation: 17605
In the situation you describe, the call
Abc.Ball();
will call the implementation in Subclass
.
Upvotes: 0
Reputation: 37023
If the Ball
method is static, it will call on super class as Ball
method is defined at class level while if it's defined at object level, then definitely it will call overridden method on sub class.
Upvotes: 1