[java] Java: Calling a super method which calls an overridden method

public class SuperClass
{
    public void method1()
    {
        System.out.println("superclass method1");
        this.method2();
    }

    public void method2()
    {
        System.out.println("superclass method2");
    }

}

public class SubClass extends SuperClass
{
    @Override
    public void method1()
    {
        System.out.println("subclass method1");
        super.method1();
    }

    @Override
    public void method2()
    {
        System.out.println("subclass method2");
    }
}



public class Demo 
{
    public static void main(String[] args) 
    {
        SubClass mSubClass = new SubClass();
        mSubClass.method1();
    }
}

my expected output:

subclass method1
superclass method1
superclass method2

actual output:

subclass method1
superclass method1
subclass method2

I know technically I have overriden a public method, but I figured that because I was calling the super, any calls within the super would stay in the super, this isn't happening. Any ideas as to how I can make it happen?

This question is related to java inheritance overriding super

The answer is


If you don't want superClass.method1 to call subClass.method2, make method2 private so it cannot be overridden.

Here's a suggestion:

public class SuperClass {

  public void method1() {
    System.out.println("superclass method1");
    this.internalMethod2();
  }

  public void method2()  {
    // this method can be overridden.  
    // It can still be invoked by a childclass using super
    internalMethod2();
  }

  private void internalMethod2()  {
    // this one cannot.  Call this one if you want to be sure to use
    // this implementation.
    System.out.println("superclass method2");
  }

}

public class SubClass extends SuperClass {

  @Override
  public void method1() {
    System.out.println("subclass method1");
    super.method1();
  }

  @Override
  public void method2() {
    System.out.println("subclass method2");
  }
}

If it didn't work this way, polymorphism would be impossible (or at least not even half as useful).


To summarize, this points to current object and the method invocation in java is polymorphic by nature. So, method selection for execution, totally depends upon object pointed by this. Therefore, invoking method method2() from parent class invokes method2() of child class, as the this points to object of child class. The definition of this doesn't changes, irrespective of whichever class it's used.

PS. unlike methods, member variables of class are not polymorphic.


"this" keyword refers to current class reference. That means, when it is used inside the method, the 'current' class is still SubClass and so, the answer is explained.


Since the only way to avoid a method to get overriden is to use the keyword super, I've thought to move up the method2() from SuperClass to another new Base class and then call it from SuperClass:

class Base 
{
    public void method2()
    {
        System.out.println("superclass method2");
    }
}

class SuperClass extends Base
{
    public void method1()
    {
        System.out.println("superclass method1");
        super.method2();
    }
}

class SubClass extends SuperClass
{
    @Override
    public void method1()
    {
        System.out.println("subclass method1");
        super.method1();
    }

    @Override
    public void method2()
    {
        System.out.println("subclass method2");
    }
}

public class Demo 
{
    public static void main(String[] args) 
    {
        SubClass mSubClass = new SubClass();
        mSubClass.method1();
    }
}

Output:

subclass method1
superclass method1
superclass method2

You can only access overridden methods in the overriding methods (or in other methods of the overriding class).

So: either don't override method2() or call super.method2() inside the overridden version.


I think of it this way

+----------------+
|     super      |
+----------------+ <-----------------+
| +------------+ |                   |
| |    this    | | <-+               |
| +------------+ |   |               |
| | @method1() | |   |               |
| | @method2() | |   |               |
| +------------+ |   |               |
|    method4()   |   |               |
|    method5()   |   |               |
+----------------+   |               |
    We instantiate that class, not that one!

Let me move that subclass a little to the left to reveal what's beneath... (Man, I do love ASCII graphics)

We are here
        |
       /  +----------------+
      |   |     super      |
      v   +----------------+
+------------+             |
|    this    |             |
+------------+             |
| @method1() | method1()   |
| @method2() | method2()   |
+------------+ method3()   |
          |    method4()   |
          |    method5()   |
          +----------------+

Then we call the method
over here...
      |               +----------------+
 _____/               |     super      |
/                     +----------------+
|   +------------+    |    bar()       |
|   |    this    |    |    foo()       |
|   +------------+    |    method0()   |
+-> | @method1() |--->|    method1()   | <------------------------------+
    | @method2() | ^  |    method2()   |                                |
    +------------+ |  |    method3()   |                                |
                   |  |    method4()   |                                |
                   |  |    method5()   |                                |
                   |  +----------------+                                |
                   \______________________________________              |
                                                          \             |
                                                          |             |
...which calls super, thus calling the super's method1() here, so that that
method (the overidden one) is executed instead[of the overriding one].

Keep in mind that, in the inheritance hierarchy, since the instantiated
class is the sub one, for methods called via super.something() everything
is the same except for one thing (two, actually): "this" means "the only
this we have" (a pointer to the class we have instantiated, the
subclass), even when java syntax allows us to omit "this" (most of the
time); "super", though, is polymorphism-aware and always refers to the
superclass of the class (instantiated or not) that we're actually
executing code from ("this" is about objects [and can't be used in a
static context], super is about classes).

In other words, quoting from the Java Language Specification:

The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.

In layman's terms, this is basically an object (*the** object; the very same object you can move around in variables), the instance of the instantiated class, a plain variable in the data domain; super is like a pointer to a borrowed block of code that you want to be executed, more like a mere function call, and it's relative to the class where it is called.

Therefore if you use super from the superclass you get code from the superduper class [the grandparent] executed), while if you use this (or if it's used implicitly) from a superclass it keeps pointing to the subclass (because nobody has changed it - and nobody could).


Further more extended the output of the raised question, this will give more insight on the access specifier and override behavior.

            package overridefunction;
            public class SuperClass 
                {
                public void method1()
                {
                    System.out.println("superclass method1");
                    this.method2();
                    this.method3();
                    this.method4();
                    this.method5();
                }
                public void method2()
                {
                    System.out.println("superclass method2");
                }
                private void method3()
                {
                    System.out.println("superclass method3");
                }
                protected void method4()
                {
                    System.out.println("superclass method4");
                }
                void method5()
                {
                    System.out.println("superclass method5");
                }
            }

            package overridefunction;
            public class SubClass extends SuperClass
            {
                @Override
                public void method1()
                {
                    System.out.println("subclass method1");
                    super.method1();
                }
                @Override
                public void method2()
                {
                    System.out.println("subclass method2");
                }
                // @Override
                private void method3()
                {
                    System.out.println("subclass method3");
                }
                @Override
                protected void method4()
                {
                    System.out.println("subclass method4");
                }
                @Override
                void method5()
                {
                    System.out.println("subclass method5");
                }
            }

            package overridefunction;
            public class Demo 
            {
                public static void main(String[] args) 
                {
                    SubClass mSubClass = new SubClass();
                    mSubClass.method1();
                }
            }

            subclass method1
            superclass method1
            subclass method2
            superclass method3
            subclass method4
            subclass method5

this always refers to currently executing object.

To further illustrate the point here is a simple sketch:

+----------------+
|  Subclass      |
|----------------|
|  @method1()    |
|  @method2()    |
|                |
| +------------+ |
| | Superclass | |
| |------------| |
| | method1()  | |
| | method2()  | |
| +------------+ |
+----------------+

If you have an instance of the outer box, a Subclass object, wherever you happen to venture inside the box, even into the Superclass 'area', it is still the instance of the outer box.

What's more, in this program there is only one object that gets created out of the three classes, so this can only ever refer to one thing and it is:

enter image description here

as shown in the Netbeans 'Heap Walker'.


You're using the this keyword which actually refers to the "currently running instance of the object you're using", that is, you're invoking this.method2(); on your superclass, that is, it will call the method2() on the object you're using, which is the SubClass.


During my research for a similar case, I have been ending up by checking the stack trace in the subclass method to find out from where the call is coming from. There are probably smarter ways to do so, but it works out for me and it's a dynamic approach.

public void method2(){
        Exception ex=new Exception();
        StackTraceElement[] ste=ex.getStackTrace();
        if(ste[1].getClassName().equals(this.getClass().getSuperclass().getName())){
            super.method2();
        }
        else{
            //subclass method2 code
        }
}

I think the question to have a solution for the case is reasonable. There are of course ways to solve the issue with different method names or even different parameter types, like already mentioned in the thread, but in my case I dindn't like to confuse by different method names.


I don't believe you can do it directly. One workaround would be to have a private internal implementation of method2 in the superclass, and call that. For example:

public class SuperClass
{
    public void method1()
    {
        System.out.println("superclass method1");
        this.internalMethod2();
    }

    public void method2()
    {
        this.internalMethod2(); 
    }
    private void internalMethod2()
    {
        System.out.println("superclass method2");
    }

}

class SuperClass
{
    public void method1()
    {
        System.out.println("superclass method1");
        SuperClass se=new SuperClass();
        se.method2();
    }

    public void method2()
    {
        System.out.println("superclass method2");
    }
}


class SubClass extends SuperClass
{
    @Override
    public void method1()
    {
        System.out.println("subclass method1");
        super.method1();
    }

    @Override
    public void method2()
    {
        System.out.println("subclass method2");
    }
}

calling

SubClass mSubClass = new SubClass();
mSubClass.method1();

outputs

subclass method1
superclass method1
superclass method2


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to inheritance

How to extend / inherit components? Inheritance with base class constructor with parameters Class is not abstract and does not override abstract method Why not inherit from List<T>? Can an interface extend multiple interfaces in Java? How to call Base Class's __init__ method from the child class? How should I have explained the difference between an Interface and an Abstract class? JavaScript OOP in NodeJS: how? When do I have to use interfaces instead of abstract classes? C++ calling base class constructors

Examples related to overriding

How to underline a UILabel in swift? How to 'update' or 'overwrite' a python list maven command line how to point to a specific settings.xml for a single command? How to override the properties of a CSS class using another CSS class What is the difference between dynamic and static polymorphism in Java? Overriding css style? Android Overriding onBackPressed() What is the 'override' keyword in C++ used for? Why do we have to override the equals() method in Java? Can overridden methods differ in return type?

Examples related to super

Equivalent of Super Keyword in C# super() raises "TypeError: must be type, not classobj" for new-style class Java: Calling a super method which calls an overridden method When do I use super()? super() in Java What is PECS (Producer Extends Consumer Super)? super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object Understanding Python super() with __init__() methods What does 'super' do in Python?