Reputation: 2094
I have scenario like
Here is the abstract class
abstract class A
{
public void add()
{
//do something
}
}
Here is the class that extends above abstract class
class B extends A
{
@Override
public void add()
{
//do something else
}
}
Here is the class in which I want to call both the add methods
class C
{
A a = new B();
// Calls B's add method
a.add();
// Call A's add method ???
}
How to call A's add method???
Upvotes: 0
Views: 4417
Reputation: 2094
I got what i want but in different way here it is how ---
class D extends A
{
public add()
{
//Log here..........
super.add();
}
}
This will help me not to force B to call default implementation of A by avoiding super.add();
As we have over-ridden it to change functionality.
class C
{
A a = new B();
// Call B's Add method
a.add();
a = new D();
// Call A's Add method via D
a.add();
}
I think there is no other better way than this :)
Upvotes: 0
Reputation: 345
class B extends A
{
//over ride method
public add()
{
//do something else
}
public add2()
{
super.add();
}
}
class C {
A a = new B();
// Calls B's add method
a.add();
// Call A's add method
a.add2();
}
Upvotes: 1
Reputation: 3163
As explained above by various people, you can't. If we try and understand as to what you want to achieve, i guess what you need is an interface and two classes.
interface AddInterface {
public void add();
}
class A implements AddInterface {
//your abstract class' version of add goes here
}
class B implements AddInterface {
//your other add definition.
}
You end up replacing references to A
with AddInterface.
Again, it all depends on what you want to achieve.
Upvotes: 1
Reputation: 1500725
You can't. That's the whole point of polymorphism and encapsulation - you've created an instance of B
, so B
gets to decide what add
means. Maybe B
is trying to enforce some business rules about when you can call add
for example - it would be useless if you could bypass those rules and call A.add()
directly on an instance of B
. The implementation of B.add()
can decide when and whether to call super.add()
, but code outside B
doesn't get to make that decision.
Upvotes: 10
Reputation: 4157
You're looking for super
.
class B extends A
{
//over ride method
public add()
{
super.add();
//do something else
}
}
Upvotes: 1
Reputation: 691755
You can't, because it would break polymorphism. If B overrides A's add
method, it's because it must add in another way to satify its contract. Not doing it the way it needs to would break B's invariants, and probably also A's invariants.
Upvotes: 1