We have parent class and child class having common method testparent() but there is difference in parameters

//Parent Class

  public class Overriding {

    int a,b,c;

   //Parameters are different in number

    public void testParent(int i, int j) {

       System.out.println(a+b);
    }
}
//Child Class Extending Parent Class Method
 class ChildOverriding extends Overriding {
      int c;

   public void testParent(int i,int j,int k) {

        System.out.println(a+b+c);
   }
  //Main Is not getting executed????
   public static void main(String args[]) {
     Overriding obj = new ChildOverriding();
     obj.testParent(1,4,8);
     }
  }
}
3

There are 3 answers

0
Mohan kumar On BEST ANSWER

Overriding Means sub class should have same signature of base class method. Parameters and return type should be the same.

1
leeyuiwah On

You can have the two methods, but then the one in ChildOverriding are not overriding the one in Overriding. They are two independent methods.

To fix your compilation problem, you have to either declare obj ChildOverriding

ChildOverriding obj = new ChilOverriding();

or you have to also implement a three-argument method in Overriding

0
Mohan Sharma On

Actually your problem here is that you're accessing a method from SubClass over a reference object of a SuperClass.

Let me explain little bit more.

Super obj = new Sub();

This line will create one reference variable (of class Super) named obj and store it in stack memory and instance of new Sub() with all implementation details will be stored in heap memory area. So after that memory address of instance stored in heap is linked to reference variable stored in stack memory.

obj.someMethod()

Now when we call any method (like someMethod) on reference variable obj it will search for method signature in Super class but when it calls implementation of someMethod it will call it from instance stored in heap memory area.

That's the reason behind not allowing mapping from Super to Sub class (like Sub obj = new Super();) becuase Sub class may have more specific method signature that can be called but instance stored in heap area may not have implementation of that called method.

So your program is giving error just because it isn't able to find method signature that you're calling in super class.

Just remember Java will always look for method signature in type of reference object only.

Answer to your question is Yes, we can have different number of parameters in subclass's method but then it won't titled as method overloading/overriding. because overloading means you're adding new behaviour and overriding means changing the behaviour.

Sorry for my bad English, and if I'm wrong somewhere please let me know as I'm learning Java.

Thanks. :)