简体   繁体   中英

calling overridden function in superclass from subclass in JAVA

Suppose I have two classes A and B where A is a superclass of B. Now, I write a function (override), say funct() in both the classes. Then, if I want to call the funct() in A from an object of B, is it possible?

class A {
    public void f() {...}
}

class B extends A {
    @Override public void f() { super.f(); }
}

Is that what you want?

If instead you want to call A#f() directly on an instance of type B, you must provide a placeholder function for that:

class B extends A {
    @Override public void f() { ... }
    public void superF() { super.f(); }
}

new B().f(); // calls B#f();
new B().superF(); // calls A#f();

I have trick such as this situation to operate it in an illogical manner using Flag argument in funct() method :D, like this:

class A {

    public void funct(boolean callSuper) {
        // avoid using callSuper arg here 
    }
}

class B extends A {

    @Override
    public void funct(boolean callSuper) {
        if (callSuper) {
            super.funct(callSuper);
            return;//if return type is void
        } else {
            //do here the functionality if the flag is false 
        }
    }
}

or

class A {

    public void funct() {

    }
}

class B extends A {

    private boolean callSuper = false;

    @Override
    public void funct() {
        if (callSuper) {
            super.funct(); // call A.funct() functionality 
            setCallSuper(false);
        } else {
            //do here the functionality of B.funct() if the flag is false 
        }
    }

    public void setCallSuper(boolean callSuper){
        this.callSuper = callSuper;
    }
}

Given classes like

class A {
    public void funct() {...}
}

class B extends A {
    @Override 
    public void funct() {...}
}

You ask

Then, if I want to call the funct() in A from an object of B, is it possible?

So let's take

B b = new B();
b.funct(); 
A a = b;
a.funct();
((A)b).funct();

The above all do the same thing because of polymorphism and late-binding.

The only way to call the superclass' implementation is to get a reference to that member through the super keyword.

class A {
    public void funct() {...}
}

class B extends A {
    @Override 
    public void funct() {
        super.funct();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM