Search code examples
javasubclasssuperclass

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?


Solution

  • 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();
        }
    }