-1
class TextClass
{
     int temp;
     void sum(int x,int y)
     {
         temp = x+y;
         System.out.println("Sum of parent class sum method = " + temp);
     }

 }
 class MethodOverriding extends TextClass
 {
    int temp;
    void sum(int x,int y)
    {
        temp = x + y;
        System.out.println("Sum of base or chlid class method = " + temp);
    }
    super.sum(10,15);

    public static void main(String args[])
    {

        MethodOverriding mo = new MethodOverriding();
        mo.sum(2,4);
        System.out.println(mo.super.sum(3,5));
    }
}

how will i use super keyword in main method here to invoke parent class sum method?

xlm
  • 6,854
  • 14
  • 53
  • 55
rahul
  • 1
  • 1
    Possible duplicate of [How to call super-version of a method that is overridden?](http://stackoverflow.com/questions/24628276/how-to-call-super-version-of-a-method-that-is-overridden) – D M Feb 01 '17 at 06:33

2 Answers2

0

You cannot access it directly from main method as main is static, Your both classes should static to call super. Otherwise like in following example, you create an object and constructor/method will call super accordingly. Which is not possible, super is non-static variable

Official docs here

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

Example: Super Class

public class SuperClass {
    public void printHello() {
       System.out.println("Hello from SuperClass");
       return;
    }
 }

Sub Class:

public class SubClass extends SuperClass {
    public void printHello() {

    super.printHello();
       System.out.println("Hello from SubClass");
       return;
    }
    public static main(String[] args) {
       SubClass obj = new SubClass();
       obj.printHello();
    }
 }

Output:

Hello from SuperClass
Hello from SubClass
Sarz
  • 1,970
  • 4
  • 23
  • 43
0

You cannot do that from the Main method.

If you want to use sum method of class TextClass,

you have to call super in MethodOverriding Class

But if you want to use both the methods you have make two different sum methods in MethodOverriding Class. One of these will call super.sum() and the other will override it

Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17