can methods be overloaded based on access in java? - 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.

Related

Why is it not allowed to give the same name to a super class final method and a sub class method? [duplicate]

This question already has answers here:
Why is it that we cannot override static and final methods? [duplicate]
(5 answers)
Closed 1 year ago.
In Java, what is the actual reason behind the inability to write a method in a sub class which has the same name as a final method in the super class? (Please note that I am not trying to override the method, this is why I have put the keyword final.)
Please see the example below:
class A {
public final void method() {
System.out.println("in method A");
}
}
class B extends A {
public void method() {
System.out.println("in method B");
}
}
The problem is expressed as "'method()' cannot override 'method()' in 'A'; overridden method is final" in the IDE; however, I would like to understand what it is about this situation that leads the compiler to fail.
Because in java, overriding isn't optional.
Names of methods at the class level.
At the class level (as in, what is in a class file, and what a JVM executes), method names include their return type and their parameter types (and, of course, the name). At the JVM level, varargs doesn't exist (it's an array instead), generics do not exist (they are erased for the purposes of signature), and the throws clause isn't a part of the story. But other than that, this method:
public void foo(String foo, int bar, boolean[] baz, long... args) throws Exception {}
turns into this name at the class file level:
foo(Ljava/lang/String;I[Z[J)V
which seems like gobbledygook, but [ is 'array of', the primitives get one letter each (Z for boolean, J for longs, I for integer), V is for void, and L is for: Object type. Now it makes sense.
That really is the method name at the class level, effectively (well, we call this its signature). ANY invocation of a method in java, at the class level, always uses the complete signature. This means javac simply cannot compile a method call unless it actually knows the exact method you're invoking, which is why javac doesn't work unless you have the full classpath of everything you're calling available as you compile.
Overriding isn't optional!
At the class level, if you define a method whose full signature matches, exactly, a signature in your parent class, then it is overriding that method. Period. You can't not. #Override as an annotation doesn't affect this in the slightest (That annotation merely causes the compiler to complain if you aren't overriding anything, it's compiler-checked documentation, that's all it is).
javac goes even further
As a language thing, javac will make bridges if you want to tighten the return type. Given:
class Parent {
Object foo() { return null; }
}
class Child extends Parent {
String foo() { return null; }
}
Then at the class level, the full signature of the one method in Parent is foo()Ljava/lang/Object; whereas the one in Child has foo()Ljava/lang/String; and thus these aren't the same method and Child's foo would appear not to be overriding Parent's foo.
But javac intervenes, and DOES make these override. It does this by actually making 2 methods in Child. You can see this in action! Write the above, compile it, and run javap -c -v on Child and you see these. javac makes 2 methods: Both foo()Ljava/lang/String; and foo()Ljava/lang/Object; (which does have the same signature and thus overrides, by definition, Parent's implementation). That second one is implemented as just calling the 'real' foo (the one returning string), and gets the synthetic flag.
Final is what it is
Which finally gets to your problem: Given that final says: I cannot be overridden, then, that's it. You've made 2 mutually exclusive rules now:
Parent's foo cannot be overriden
Child's foo, by definition (because its signatures match), overrides Parent's foo
Javac will just end it there, toss an error in your face, and call it a day. If you imagined some hypothetical javac update where this combination of factors ought to result in javac making a separate method: But, how? At the class level, same signature == same method (it's an override), so what do you propose? That java add a 0 to the end of the name?
If that's the plan, how should javac deal with this:
Parent p = new Child();
p.foo();
Which foo is intended there? foo()Ljava/lang/Object; from Parent, or foo0()L/java/Object; from child?
You can write a spec that gives an answer to this question (presumably, here it's obvious: Parent's foo; had you written Child c = new Child(); c.foo(); then foo0 was intended, but that makes the language quite complicated, and for what purpose?
The java language designers did not think this is a useful exercise and therefore didn't add this complication to the language. I'm pretty sure that was clearly the right call, but your opinion may of course be different.
Final means not just that you can’t override it, it means you can’t work around having that method get called.
When you subclass the object, if you could make a method that shadows that final method, then you could prevent the superclass method from functioning, or substitute some other functionality than what the user of the object would expect. This would allow introducing malicious code and would defeat the purpose of making methods final.
In your case it sounds like making the superclass method final may not have been the best choice.

Can a class have two no-args methods with same name?

Reading documentation:
https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.html
I was confused by this sentence:
The service provider class file has more than one public static no-args method named "provider".
Assuming JavaDoc is correct, and assuming that static members are not inherited, how this might be possible in Java? Or it's an error in JavaDoc?
how this might be possible in Java?
It is not, since method signatures must be unique, and the signature is the method name and parameter types.
Except, that is not how the JVM works, only how Java works.
The JVM includes the return type as part of the signature, so technically a class can have multiple methods with the same name and parameters, but different return types.
So it can definitely happen for classes written in other JVM languages, but can it happen for a Java class?
Yes it can, when you have covariant return types for overridden methods. See Can overridden methods differ in return type?
Given the example in that answer, what really happens is this fake code:
class ShapeBuilder {
...
public Shape build() {
....
}
class CircleBuilder extends ShapeBuilder{
...
#Override
public bridge Shape build() { // override matches full JVM signature
return <Circle>build(); // call other method with different return type
}
public Circle build() {
....
}
The "bridge" method is a hidden method generated by the compiler to make the difference between Java and the JVM work correctly.
FYI: In that aspect, "bridge" methods are similar to "synthetic" methods, which are generated by the compiler to allow outer classes access to private members of inner classes, or vice versa.

Reducing the visibility of a static method

I know that a child cannot reduce the visibility of a non-static method and I understand why it is so.
I've read however that "static method can be hidden through its redeclaration". I however do not understand how this could be achieved in Java.
Is this really possible? If yes, how to do that (code example) and why was it introduced (it seems to contradict the principle of non-reducing the visibility of the interface)?
The short answer is: no, it is not possible. You have mixed up some terminology. Hiding has nothing to do with accessibility (which is what you are really asking about, not visibility, which is related to scope and shadowing and is discussed in Chapter 6 of the Java Language Specification (JLS)).
Now for the longer answer. The term overriding applies to instance methods, while the term hiding applies to class (static) methods. From the Java Tutorial topic Overriding and Hiding Methods:
The distinction between hiding a static method and overriding an instance method has important implications:
The version of the overridden instance method that gets invoked is the one in the subclass.
The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Some of the other answers here provide incorrect examples about method hiding, so let's go back to the JLS, this time to §8.4.8:
Methods are overridden or hidden on a signature-by-signature basis.
That is, to override or hide a method in the parent class, the subclass must define a method with the same signature—basically, the same number and type of arguments (although generics and type erasure makes the rules a little more complicated than that). There are also rules about return types and throws clauses, but those seem irrelevant to this question.
Note that you can define a method in a subclass with the same name as a method in the parent class (or in an implemented interface) but with different number or type of arguments. In that case, you are overloading the method name and neither overriding nor hiding anything; the subclass method is a new method, pretty much independent of the inherited method(s). (There is an interaction when the compiler has to match methods to method calls, but that's about it.)
Now to your question: the terms accessibility and hiding (as well as visibility) are independent concepts in Java. There is, as you put it, a "principle" that there is simply no way for a subclass to reduce the accessibility of an inherited method. This applies regardless of whether you are overriding an instance method or hiding a class method. From the JLS §8.4.8.3:
The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:
If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.
If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.
If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.
In summary, the fact that a static method can be hidden has nothing to do with changing the accessibility of the method.
Based on hagubear's valuable comments, it seems that the author of a statement meant hiding a method through overloading it with a method having the same declaration.
Quoting this link:
We can declare static methods with same signature in subclass, but it
is not considered overriding as there won’t be any run-time
polymorphism. (...) If a derived class defines a
static method with same signature as a static method in base class,
the method in the derived class hides the method in the base class.
Thus, defining a method in a child class having exact same declaration effectively hides the original method in child. However, as in case of fields, casting to the parent will restore the original access.
Sample code:
public class Test {
public static void main( String[] args ) {
B b = new B();
A a = b;
b.f(); // "Access somewhat denied"
a.f(); // "f()"
}
}
class A {
public static void f() {
System.out.println("f()");
}
}
class B extends A {
// *must* be public
public static void f() {
System.out.println("Access somewhat denied");
}
}
So I created a trivial test; IntelliJ indeed rejected it... and Yes, I know "it's a tool...but one I trust". In any case, I went to javac, which emitted the same ERROR:
Error:(...) java: ...Concrete.java:5: doSomethingStatic() in
...Concrete cannot override doSomethingStatic() in
...Base; attempting to assign weaker access privileges; was public
Based on this, and our skepticism in general, I suggest the error is in your documentation.
Below is my sample code, fairly definitive I think. It barfs at the protected.
public class Base
{
public static void doSomethingStatic(){}
}
public class Concrete extends Base
{
protected static void doSomethingStatic(){}
}
It can be hidden by an overloaded redeclaration in a derived class:
class Base
{
public static void doSomethingStatic(){}
}
class Derived extends Base
{
public static void doSomethingStatic(String arg){}
}
but only hidden to people who try to access it via the derived class.

Which constructor is called first while passing null in the class having overloaded constructor?

Below is the java class having 3 overloaded constructors :
public class Test {
public Test(Object i){
System.out.println("Object invoked");
}
public Test(String i){
System.out.println("String invoked");
}
public Test(int k){
System.out.println("Integer invoked");
}
public static void main(String[] args) throws Exception {
Test t = new Test(null);
}
}
If null value is passed while creating the new instance of class, which constructor will be invoked ? What is the reason ?
Java always chooses the most specific method (or constructor) that would be applicable for the argument you pass. In this case, that's the String constructor -- String is a subclass of Object.
Think about what would happen if you had
new Test("some string")
Both the Object and String constructors would be applicable here. After all, the argument is both an Object and a String. However, it is clear that the String constructor will be invoked because it is more specific than the Object constructor and still is applicable given the argument.
null is no different; these two constructors are still applicable, and the String constructor is still chosen over the Object one for the same reason.
Now, if there were two equally "specific" constructors present (e.g. if you had an Integer constructor) there would be a compilation error when you call Test(null).
This is outlined in more detail in JLS §15.12.2:
The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.
There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.
The explicit process of determining which method is the most specific is outlined in JLS §15.12.2.5.
The answer is: Test(String) is invoked.
Why?
When determining which of a set of overloaded methods will be invoked, the Java compiler will attempt to match the most concrete type. And it will first attempt to match a signature before employing autoboxing. (#arshajii provided a perfect reference into the Java Language Spec on this)
Here, Object is the most abstract class in the type system. String subclasses from Object and is therefore more specific/concrete.
The logic behind this is that if you are overloading a method with a more specific-typed parameter, you're likely wanting to do more with that object (when you subclass, you typically add methods). If method signature determination worked the other way (i.e. the more abstractly-typed signature winning; here, Test(Object)), then none of the more concrete signatures would ever get called.

Method Overriding of diffrent Return type to void

let's say we have this method
public class Animal {
public void eat() { }
}
and on another class that extends Animal has this method
public String eat(){}
is this considered as method overriding? because I've heard that you can use different return types in method overriding providing they have the same method arguments
This is neither overloading , nor overriding ! It is compilation error .
In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.
Following are rules of method overriding in java which must be followed while overriding any method. private, static and final method can not be overridden.
1)Method signature must be same including return type, number of method parameters, type of parameters and order of parameters.
2)Overriding method can not throw higher Exception than original or overridden method. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
3)Overriding method can not reduce accessibility of overridden method , means if original or overridden method is public than overriding method can not make it protected.
You can only change the return type to a subclass of the original return type.
All answers are correct from a technical point of view because Void is a class in Java that no other class can extend and when methods are overridden the return-type has to be a sub-type of the original type (parentReturnType.isAsignableFrom(overriddenReturnType)).
But from a practical point of view the question is still valid and it would have made sense to make an excuse for the special case void. The only value a variable of the type Void can hold is null. Further no variable can have the primitive type void. Finally you can not compile this code:
Void result = object.notify();
So in the end it would have made sense to specify Java differently when 1.5 was introduced and allow overriding void return types with any other type.
Therefore the only reasonable answer is IMHO it is not possible because Java was designed such that this is not allowed.
This not correct Code, as two methods with same name should return same value, only arguments can be differents
Overriding is having same method with same arguments in the subclass
Overloading having same method name with different argumens
The return type of a method is not part of that method's signature.
When you call eat() on the subclass, java looks at the signature you provided (eat with no parameters) and starts looking for a method with this signature, starting in the class of the instance type of the object you call it on (and searches through its ancestors if it fails to find it).
So, methods called on a subclass will always run the overridden methods (they're found first).
A critical 'point' of OO (specifically polymorphism) is that a subclass can be passed in where the superclass was expected.
If a method wants to call the superclass' eat() method and get a void, but you passed a subclass into that method of which eat() returned a String; you can see that method will call the subclass' eat and get an unexpected value.
You can see why this could be a problem. :I
So, overriding methods must return the same type or a subclass of the type returned by the parent.
(Similar principles apply as to why you can return a subclass; I'll let you think about it c: )
It's neither overriding nor overloading, it creates compilation error.
Two methods with same name, different param numbers or different type of params known as overload method, return type may be same or different. It may be in same class or parent, child classes.
Two methods having same param numbers, same types, same return types but one is in parent class and other is in child class are known as overrided methods.

Categories

Resources