In: Computer Science
Q. Explain how to invoke a superclass method from a subclass method for the case in which the subclass method overrides a superclass method and the case in which the subclass method does not override a superclass method. [1 Mark]
this is a correct answer but i want answer it in different way :
In the case where the subclass method overrides the superclass method, it is necessary to explicitly use the keyword super, to invoke the method of the superclass as super.methodName().
When the subclass method does not override the superclass method, the superclass method can be invoked simply by using its name and appropriate arguments.
ANSWER:
Case 1: When a method of super class is overridden by a method of the sub class
To call a method of a superclass from a subclass when the method being called is overridden by a method of the subclass, super keyword is used. For example:-
class SuperClass { SuperClass() {} public void foo(){ System.out.println("In super class's foo"); } } class SubClass extends SuperClass { SubClass() {} //Overridden method of superclass @Override public void foo(){ System.out.println("In sub class's foo"); } //Method of sub class which calls foo() method of super class public void bar() { super.foo(); } } //Main class public class Main { public static void main(String[] args) { SubClass obj3 = new SubClass(); obj3.bar(); } }
In this example, the method bar() of SubClass calls the method foo() of SuperClass which is overridden in SubClass. In this case, there is no other way of calling the foo() method of SuperClass other than using super keyword.
Case 2: When a method of super class is not overridden by a method of the sub class
In this case, to call a method of the superclass we can simply use the name, with proper parameters, of the method of the superclass to call the method. For example:-
class SuperClass { SuperClass() {} public void foo(){ System.out.println("In super class's foo"); } } class SubClass extends SuperClass { SubClass() {} //Method of sub class which calls foo() method of super class public void bar() { foo(); } } //Main class public class Main { public static void main(String[] args) { SubClass obj3 = new SubClass(); obj3.bar(); } }
In this example, the foo() method of SuperClass has not been overridden in the SubClass. Therefore, we can simply call the foo() method of the SuperClass by using its name.