+ 1
Is this Overriding?
class A{ void pro(int enroll, String name) { } } class B extends A { int pro(int enroll, String name) { return 0; } }
8 Answers
+ 5
Dan Technically yep but when it comes to inheritance, to actually be overriding a method of the parent class, wouldn't we need to account for the return type?
+ 3
This would actually generate a compilation error. These methods are ambiguous for the program as there is no way to decide which one to call based on the parameters. This is why, even in principle, you can't override with return type. If the parameters were different (either type or number of parameters) then this would be overloading as cyk said
edit: in order to override the method, the method signature should be the same. This way, whenever an object of type B is used (even if assigned as an A) the method will be overridden e.g.
A obj = new B();
obj.pro(1, "foo");
would call the method in B
+ 3
No. For it to be overriding the two functions must have the same number of parameters, the same data types for the parameters and the same return type. Here the return type is different.
This is to add to Dan's answer about why it is not overloading as I said in an earlier, now deleted, post.
+ 2
Dan I had already deleted it. 🙄
+ 1
cyk personally I'd leave it as it forms part of the discussion, and your answer is correct in principle :p there's just an additional factor to consider
+ 1
cyk technically, to override a method the signatures should be the same, which is the method name and number/order/types of parameters. The signature doesn't include the return type or thrown exceptions :)
+ 1
cyk In fact it is possible to narrow the scope of a return type when overriding, so a parent class/interface that returns a Collection could have a subclass with an overriding method that returns a List (after Java 5)
0
Overriding means providing another implementation of method of super class in child class keeping in mind that method signature is same as parent class and return type can be of child class and if exception is thrown, child class implementation throws sub-class exception or parent class exception.
For e.g.
class A {
T methodA() {
}
}
class B extends A {
T methodA() {
}
}
Read more on overriding:- http://crbtech.in/Java-Training/method-overloading-overriding-java-2/



