Sign in to follow this  
chand81

[java] Disable Polymorphism

Recommended Posts

How to make sure that the Func2(); call in Transformable.Func1 calls Transformable.Func2 and not Camera.Func2 In c++, I simply do Transformable::Func2(); - what is the Java counter part? Thanks. class Transformable { void Func1() { Func2(); } void Func2() { } } class Camera extends Transformable { void Func1() { super.Func1(); } void Func2() { super.Func2(); } }

Share this post


Link to post
Share on other sites
Quote:
Original post by chand81
How to make sure that the Func2(); call in Transformable.Func1 calls Transformable.Func2 and not Camera.Func2

In c++, I simply do Transformable::Func2(); - what is the Java counter part?
Thanks.

class Transformable
{
void Func1()
{
Func2();
}

void Func2()
{
}
}


class Camera extends Transformable
{
void Func1()
{
super.Func1();
}

void Func2()
{
super.Func2();
}
}


If you make the class final, then calls will not be made through virtual dispatching. Also, the JVM has the ability to detect if a class is not extended at runtime and can disable polymorphism then as well. If a class is extended, it will always go through the vtable, I believe.

Share this post


Link to post
Share on other sites
Hmm, let me get this right:
You have an instance of a sub-class, for which you want a parent's method to be called in place of the overridden method in the sub-class. Now presumably you won't be able to just write super.parentMethod() in the sub-class method otherwise you wouldn't have needed to override it in the first place.

I thought I recalled being able execute the method of an arbitrary ancestor of the real class with some weird syntax, but all of the resources I checked seem to deny this (with good reason).

What you really want to do is either remove Func2() from Camera (since then any call to Func2() on a Camera object will invoke the Transformable version of Func2(). OR you could just rename Func2() in Transformable so that it doesn't get overriden at all. Because if you don't want polymorphic behaviour, then it should be Func3() or something.

Share this post


Link to post
Share on other sites
The best thing to do is probably to create a third, private function in Transformable that implements the desired Func2 behavior. The external interface exposes Func2, allowing it to be overridden while the internal interface can still use the base class behavior by calling Func3.


class Transformable
{
void Func1()
{
Func3();
}

void Func2()
{
Func3();
}

private void Func3()
{
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this