Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Can I override parent method but with different parameter?

Tags:

java

There are 2 classes. Parent class has method --> public void abcd(int i) and child class has override that -->public void abcd(Integer i)

Is this possible because same method name but int used in parent class and Integer I have been used in child class.

Practice.java

public class Practice {
  public void abcd(int i){
   System.out.println("Hi");
  }

Practice2.java

public class Practice2 extends Practice{
 public void abcd(Integer i){
  System.out.println("oh child");
 }
 public static void main(String[] args) {
  Practice p = new Practice();
  Practice p2 = new Practice2();
  p2.abcd(1); //Is this possible
 }

}

I got this below error The method abcd() in the Practice is not applicable for the arguments(int) int and Integer are same right? why it is not accepting?

like image 324
Mohammed Sajjad Avatar asked Sep 10 '26 10:09

Mohammed Sajjad


1 Answers

No it is not possible. According to the Java docs

To override a parent method ,child must use same signature (name, plus the number and the type of its parameters) and return type(covariant return type allowed here)

like image 75
Prabhaker A Avatar answered Sep 11 '26 23:09

Prabhaker A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!