简体   繁体   中英

can methods be overloaded based on access in java?

For example a class has public do, packaged do, protected do, and private do. If an instance of the class calls do it gets the private one, if a subclass calls it, then it gets protected, if a same package calls it, then it gets packaged and if anything else calls it, it gets public?

No.

It is a compile-time error to declare two methods with override-equivalent signatures (defined below) in a class. Two methods have the same signature if they have the same name and argument types.

(From JLS §8.4.2 )

class A
{
    public Object do() { ... }
    protected Object do() { ... }
    Object do() { ... }
    private Object do() { ... }
}

No. This will not compile with or without a subclass. Nor should it be expected too. How would the compiler have any idea which method to invoke? It's impossible.

To maybe make it a little clearer, a more distinctive overload--one that returns some other type than Object is not even an acceptable overload because the compiler would still have trouble determining which method to call. A weaker form of overloading would be even less acceptable.

No. This is an element that comprises its identity (just as you can't overload the name or return type of the method). You can only overload which variables are passed to the method.

If you tried to make a method public whose super method was private, you would get a compiler error, and your program would not run.

No, because this methods all have the same method signature :

Definition: Two of the components of a method declaration comprise the method 
signature — the method's name and the parameter types.

Compiler can only distinguish between methods based on their signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM