This question already has answers here:
Is it possible to have different return types for a overloaded method?
(13 answers)
The relationship of overload and method return type in Java?
(4 answers)
Closed 6 years ago.
I am gonna put this question to have a clear idea about overloading Concept in java . As per my understanding while method resolution in overloading compiler will look for method signature that is it should have same method name and different argument types . But what if the return type is different ??
class Test{
public void m1(int i) {
System.out.println(" int arg");
}
public int m1(String s) {
System.out.println("String-arg");
return (5+10);
}
public static void main (String[] args) throws java.lang.Exception
{
Test t = new Test();
t.m1(5);
int i = t.m1("ani");
System.out.println(i);
}}
the above program is running perfectly . my doubt here is , the method m1() is it overloaded ?? it has different return type . someone please make it clear. Thanks in advance
In Java methods are identified by name and arguments' classes and amount. The return type doesn't identify the method. For this reason the following code would be illegal:
public void m1(String i) {
System.out.println(" int arg");
}
public int m1(String s) {
System.out.println("String-arg");
return (5+10);
}
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. (...) When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4)
Summarizing, two methods with the same name can return different types, however it's not being taken into account when deciding which method to call. JVM first decides which method to call and later checks if the return type of that method can be assigned to the certain variable.
Example (try to avoid such constructions):
public int pingPong(int i) {
return i;
}
public String pingPong(String s) {
return s;
}
public boolean pingPong(boolean b) {
return b;
}
if we follow the Oracle definition then yes, it is a overloaded method
here the info (emphasis mine)
The Java programming language supports overloading methods, and Java
can distinguish between methods with different method signatures. This
means that methods within a class can have the same name if they have
different parameter lists (there are some qualifications to this that
will be discussed in the lesson titled "Interfaces and Inheritance").
the fact that the method return a value or not is IRRELEVANT for the overloading definition...
another thing is here why can a method somethimes return a value and sometimes no...
this will drive crazy the people using the code, but that is another question...
Related
This question already has answers here:
When overriding equals in Java, why does it not work to use a parameter other than Object?
(7 answers)
Overloaded method selection based on the parameter's real type
(7 answers)
Closed 6 years ago.
I have this code in java and I do not understand the meaning of the Object in the following code ...
Here is the code
public class Tester {
public static void main(String[] args) {
Foo foo1 = new Foo(1);
Foo foo2 = new Foo(2);
System.out.print(foo1.equals(foo2));
}
}
class Foo {
Integer code;
Foo(Integer c) {
code = c;
}
public boolean equals(Foo f) {
return false;
}
public boolean equals(Object f) {
return true;
}
}
When I run the code I get false
but when I remove
public boolean equals(Foo f) {
return false;
}
and run the code I get true...
Why is that and what is happening ?
Thanks
This is method overloading resolution. There are two method candidates, one that takes an Object and the other takes Foo, when you pass a Foo, the most specific method (the one that takes Foo) will be called.
When you remove the method that takes Foo, you won't have an overload any longer and because Foo is an Object (as any class in Java) the method will accept it.
Method Overloading. Most specific method gets chosen at run time.
As per Language specification most specific method chooses at run time.
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
You are getting false because most specific method got choosen. That is the reason
public boolean equals(Foo f) {
return false;
}
This method called and returning false. When you remove this method,
public boolean equals(Object f) {
return true;
}
This gets called because every Foo is Object.
Because the compiler is going to invoke the most-specific method matching the parameters. When you have equals(Foo) that is more specific than equals(Object). When you remove equals(Foo) the equals(Object) is the only method that is still valid. It is also worth noting that Foo has an implicit parent class, java.lang.Object.
i think you don,t really understand object oriented programming, you should get a book on OOP to understand the consepts. check it-ebboks.com for some helpfull books
An objact is an instance of a class, take for instance a classroom of student offering the same subjects , if john doe is a memebr of that class that is he offers the courses in that class he is an instance of that class
public boolean equals(Foo f) {
return false;
}
is returning false no mattter what parameter you pass into it
In overloading when we overload a method why we cant make a new method which works same as overloaded method because we have to write the same number of line of code Such as in my example...why i cant make a new method b() which multiply two numbers.
public class que {
public void a(int a)
{
System.out.println(a);
}
public void a(int b,int c) {
System.out.println(b*c);
}
public static void main(String[] args) {
que queObject = new que();
queObject.a(5);
queObject.a(3,4);
}
}
You can make all your methods have different names. The point is you don't have to. This reduces the number of names a developer using the API needs to learn.
e.g. in the PrintWriter you have lots of methods called print and println which conceptually all do the same thing. They could have been given different names, but then you would need to know which method you wanted to call,
At runtime, each method signature is unique as it includes the return type and the non generic argument types form. i.e. in byte code the names are made unique for you.
In Java, a method cannot be distinguished/overloaded by it's return type, though in Java 6 there was a bug which allowed overloading on methods with different return types.
Nobody says you can't do this. It just isn't method overloading. That's defined as two or more methods of the same name, but with different (parameter) signatures.
method name signifies what a method does. so if you have 2 methods having same name but expects different arguments. its beneficial for the understanding of code and better design to have the same name.
so if you add another method
public void a(int b,int c,int d) {
System.out.println(b*c*d);
}
you basically doing the same behaviour i.e. multiplication but with more arguments. so overriding is better for understanding and good coding principles.
Consider This
public void eat(Orange o) {
// eat Orange
}
public void eat(Mango m) {
// eat Mango
}
You want different implementation on the basis of what you pass as a parameter but want to keep method name same.
For More Info --> Polymorphism vs Overriding vs Overloading
Here's my explanation:
public class Calculator {
// used for integer numbers
public int sum(int a, int b) {
return a + b;
}
// used for double numbers
public double sum(double a, double b) {
return a + b;
}
}
In this case you don't care if you use sum method with int or double - sum method is overloaded, so it will take both int and doubles. It's much easier than using sumInts() and sumDoubles() separately.
Method overloading is when, in a class, there are more than one method with same name but different arguments although it can have different return types (different return types is in itself is not a distinguishing feature and if only that is changed will result in a compile error).
For a complete discussion, see: http://beginnersbook.com/2013/03/polymorphism-in-java/
Why do we need it?
An example will be enlightening: Lets take the ubiquitous StringBuilder class and its append methods. They are a prime example of overloading. A specific instance of method overloading is constructor overloading as well. See the StringBuilder again: http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html.
As another example suitable to your case: we can have an appendBoolean(boolean b) and a appendString(String b) and a appendChar(char c) in the StringBuilder class as well. It is a matter of clarity and choice to either have that or just have a set of overloaded append methods. To me - since the operation is to append but we are appending different instance types - having an overloaded append makes sense and provides clarity and is concise. On the other hand, you have no such choice for overloaded constructors: they need to have the same name as the class - that is by convention and by design :-)
This question already has answers here:
Which overload will get selected for null in Java?
(3 answers)
Closed 8 years ago.
When i run this code the output is "String"; if I hide the method that accepts a String parameter and run the code again then the output is "Object", so can anyone please explain me how this code works?
public class Example {
static void method(Object obj) {
System.out.println("Object");
}
static void method(String str) {
System.out.println("String");
}
public static void main(String args[]) {
method(null);
}
}
Compiler will choose most specific method, in this case, String is a sub class of Object, so the method with String as argument will be invoked.
From JLS 15.12.2.5
If more than one member method is both accessible and applicable to a
method invocation, it is necessary to choose one to provide the
descriptor for the run-time method dispatch. The Java programming
language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than
another if any invocation handled by the first method could be passed
on to the other one without a compile-time type error.
This question already has answers here:
Java method dispatch with null argument
(4 answers)
Closed 9 years ago.
public class Overloading {
public static void main(String[] args) {
Overloading o = new Overloading();
o.display(null);
}
void display(String s) {
System.out.println("String method called");
}
void display(Object obj) {
System.out.println("Object method called");
}
}
It is giving the output as "String method called". I need the explanation why?
Taken from the Java Spec:
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
First of all: both methods are accessible (obviously) and applicable. They are both applicable, because null is of type nulltype, which is by definition a subtype of all types. String is more specific than Object, because String extends Object. If you would add the following, you will have a problem, because both Integer and String are equally "specific":
void display(Integer s) {
System.out.println("Integer method called");
}
Java will always find the most specific version of method that is available.
String extends Object, and therefore it is more specific.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5
I've been studying because I have an exam and I don't have many problems with most of Java but I stumbled upon a rule I can't explain. Here's a code fragment:
public class A {
public int method(Object o) {
return 1;
}
public int method(A a) {
return 2;
}
}
public class AX extends A {
public int method(A a) {
return 3;
}
public int method(AX ax) {
return 4;
}
}
public static void main(String[] args) {
Object o = new A();
A a1 = new A();
A a2 = new AX();
AX ax = new AX();
System.out.println(a1.method(o));
System.out.println(a2.method(a1));
System.out.println(a2.method(o));
System.out.println(a2.method(ax));
}
This returns:
1
3
1
3
While I would expect it to return:
1
3
1
4
Why is it that the type of a2 determines which method is called in AX?
I've been reading on overloading rules and inheritance but this seems obscure enough that I haven't been able to find the exact rule. Any help would be greatly appreciated.
The behavior of these method calls is dictated and described by the Java Language Specification (reference section 8.4.9).
When a method is invoked (§15.12), the number of actual arguments (and
any explicit type arguments) and the compile-time types of the
arguments are used, at compile time, to determine the signature of the
method that will be invoked (§15.12.2). If the method that is to be
invoked is an instance method, the actual method to be invoked will be
determined at run time, using dynamic method lookup (§15.12.4).
In your example, the Java compiler determines the closest match on the compile type of the instance you are invoking your method on. In this case:
A.method(AX)
The closest method is from type A, with signature A.method(A). At runtime, dynamic dispatch is performed on the actual type of A (which is an instance of AX), and hence this is the method that is actually called:
AX.method(A)
I will clarified it in more simple way. See when you making sub class object with super class reference like here you did.
Always one thing keep in your mind that when you call with super class reference, no matters object is of sub class it will go to the super class, check method with this name along with proper signature is there or not.
now if it will find it, than it will check whether it is overridden?? if yes than it will go to the sub class method like here it went. another wise it will execute the same super class method.
I can give you the example of it...just hide
public int method(A a) {
return 3;
}
method & check your answer you will get 1 2 1 2, why because it gives first priority to reference. because you overridden it & than calling it, so its giving 3..!! hope its big but easy to understand. Happy Learning
a2 referenced as an A and the JVM using the reference first (not the acutal object as you expected).