开发者

can methods be overloaded based on access in java?

开发者 https://www.devze.com 2023-03-05 19:16 出处:网络
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 protec

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消