Home > Mobile >  If a java class have to methods of the same name but one has static and the others dont which one do
If a java class have to methods of the same name but one has static and the others dont which one do

Time:11-17

public class test2 {

    public static void main(String[] args) {
        A a = new A();
        int y = 5;
        System.out.println(a.foo(y));
    }
}

class A{
    public A() {
        
    }
    public int foo(int x) {
        return x 1;
    }
    public static int foo(int x) {
        return x 2;
    }
}

If a java class has two methods of the same name but one has static and the other doesn't which one does it execute? Why does it prioritize the one on top? Or is it because the first foo does not have static?

CodePudding user response:

Java language specification , is very clear about it. Static and non-static methods can overload each other.

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.9

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

Though in your example , it will be compile error since signature is same (nt foo(int x)).

The following is complete valid.

public int foo(int x){
        return x;
    }

    public static float foo(float y){
        return y;
    } 

IMO, Practically its not a good practice to have mixed overloading (static and non-static)

CodePudding user response:

If It is of same name and one is static and other isnt, It will not work
If Both Functions Have Different parameters then if you call the function it will try to match the arguments given with the parameters in both same name functions. and will call the functions which have exact same arguments.
NVM my English

  • Related