0

I have two java class files

Hi.java which belongs to second package

package second;

public class Hi {
protected int v=20;
protected void m(){
    System.out.println("i am protectTED");
}
}

S.java which belong to first package

 package first;
import second.Hi;
interface i1
{
void m();
int a=200;
}
interface i2{
void m1();
int b=100;
}
class S extends Hi implements i1,i2
{
int a=50;
public void m()
{
    System.out.println("hi");
}
public void m1()
{
    System.out.println("hello");
}
public static void main(String[] args) {
    S s=new S();

    /*need correction here (i don't know the exact syntax to mention to get 
    the desired output)
    s.m(); //should invoke method m() from class Hi only.
    s.m(); //Should invoke method m() from class S only.
    */

    //the following statements prints the desired values

    s.m1();
    System.out.println(s.v);
    System.out.println(i1.a);
    System.out.println(s.a);
    System.out.println(b);

}
}

when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.

How to differentiate the 2 methods for invoking. Is it even possible?

  • 1
    That's the way method overriding behaves in Java. In order to "differentiate" the methods, they'll need to have different signatures. – Eran Aug 07 '17 at 11:02
  • https://stackoverflow.com/questions/22343982/calling-super-class-method ? –  Aug 07 '17 at 11:07

1 Answers1

1

when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.

Correct, because you've overridden it with m in S. Overriding methods is fundamentally different from overriding fields. (And in general, it's best to avoid overriding any fields that are visible to your subclass, as you're doing with a.)

In instance code in S, you can run the inherited m via super: super.m(). But you cannot do that from static code, not even static code in S. You could give yourself a private callSuperM in S:

private void callSuperM() {
    super.m();
}

...and then use that in main:

s.callSuperM(); // "i am protectTED"
s.m();          // "hi"
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875