Is it overloading or overriding? - java

I have a code and I am not able to get why the output will be "Radial Tire with long".Can somebody help me to understand this code?
class Tyre {
public void front() throws RuntimeException {
System.out.println("Tire");
}
public void front(long a) {
System.out.println("Radial Tire with long");
}
}
class TestSolution extends Tyre {
public void front() {
System.out.println("Radial Tire");
}
public void front(int a) throws RuntimeException {
System.out.println("Radial Tire with int");
}
public static void main(String... args) {
Tyre t = new TestSolution();
int a = 10;
t.front(a);
}
}

front is not overridden in TestSolution, it is overloaded.
You can regard an overloaded function as a completely different function, like one with a different name.
So t.front(a) will call the one in Tyre, with an a implicitly converted to long.

So if we go with definitions
Overloading means methods with same name but with different number or order of parameters.
Overriding means method with same name with same number of parameters along with rules mentioned here
So in your case front method is overloaded in both the classes Tyre and TestSolution
method front() from Tyre class is overridden in class TestSolution.
no overriding in case of method front(long a) and front(int a).

There's no overriding taking place in your main.
t's static (compile-time) type is Tyre, so, since method overload resolution is determined by the compile-time type of the instance, the only front methods available for the compiler to choose from are those declared in the base class Tyre :
public void front()
public void front(long a)
Only the latter (public void front(long a)) matches the arguments of the call t.front(a), and that method is not overridden by the sub-class. Therefore Radial Tire with long is displayed.
Calling ((TestSolution)t).front(a); would invoke the sub-class's method - public void front(int a).

General rule: if I have a variable of one class I can access only methods and components defined in that class.
The only particular case is:
you have a component or method both in the super class and in the subclass (overriding)
you have a variable of the super class and an object of the subclass (your case)
In these cases you can follow the following rule:
for the components the type of the variable decides which to use
for the methods the type of the object does (late binding)
In your case as stated before the method is not overridden so you can't apply the last rule.

Lets understand the difference between overloading and overriding
Overloading:
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
Overriding:
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
Tyre declared front() method with long as parameter.
TyreSolution declared front() method with int as parameter.
Since the method signature is different, TyreSolution overloads Tyre's front() method
If you change signature of front() in TyreSolution to accept long value as input parameter instead of int, then TyreSolution overrides Tyre's front() method.
e.g. TestSolution class definition of front() method
public void front(long a) throws RuntimeException {
System.out.println("Radial Tire with long in TestSolution");
}
output:
Radial Tire with long in TestSolution

Related

Method overloading or overriding?

We have a Parent and child class, which has method with the same name but argument are as primitive and wrapper. Could someone please explain the reason whether this would be referred as Method Overriding and Method overloading. Running this program would invoke Parent method - which would be overriding and not overloading, looking for explanations.
class Parent {
public void takeValue(int a) {
System.out.println("take value method from parent is invoked");
}
}
class Child extends Parent {
public void takeValue(Integer a) {
System.out.println("take value method from child is invoked");
}
public static void main(String[] args) {
Parent p = new Child();
p.takeValue(new Integer(51));
}
}
The method is overloaded.
Running this program would invoke Parent method - which would be overriding and not overloading
Yes. You're calling takeValue on a Parent variable, which means that the compiler will look for a signature match on the Parent class. The overload is not even visible here (signatures are matched based on static types, i.e., java finds the method based on the declared data type of the variable on which the method is called, not with the data type of the object assigned to the variable, which would be a runtime thing).
And because public void takeValue(Integer a) is not considered by the compiler when checking the method invocation, p.takeValue(new Integer(51)); is linked to Parent.takeValue(int) by virtue of autoboxing (it would have matched the other method if both of them were visible - or declared in the Parent class in this example).
This is overloading. You have same name but type of input parameters are different.
To confirm that, you will get an error when you try to attach the #Override annotation.
Integer and int are different types.

Overloading overridden method am I overloading parent or sub-class method

Overloading overridden method in subclass, am I overloading parent method or sub-classes method?
I understand generally what overloading and overriding is.
Overloading - same method different parameters and maybe return type in the same class.
Overriding - in subclass same method signature as in parent but different implementation.
class A {
public void a() {
System.out.println("A.a");
}
}
class B extends A {
public void a() {
super.a();
System.out.println("B.a");
}
public void a(int x) {
}
}
Is method B.a(int x) overloading A.a or B.a?
You override something that is inherited, so B.a() overrides A.a(). Overriding means to redefine.
Overloading is when your class have more than one definition of the same method name (each with different argument types). In B, the name a is overloaded. There is B.a() and B.a(int x).
Some of the definitions might be inherited. So if you remove B.a(), the class B would still have a method a() since it inherits it from A. And the method name a would still be overloaded in B.
Method B.a(int x) overloads B.a(), since method overloading resolution takes place at compile time, and depends on the compile time type of the variable for which you are calling the method.
On the other hand, the decision of which overridden method to execute takes place at runtime, and depends on the run-time type of the instance for which you are calling the method.
You can see that by trying the following code, which won't pass compilation, since class A has no method of the signature a(int x):
A b = new B ();
b.a(4);
b.a(int x ) is overLoading a method of class B.a()
Rules of Overriding
Rule #1: Only inherited methods can be overridden.
Rule #2: Final and static methods cannot be overridden.
Rule #3: The overriding method must have the same argument list.
Rule #4: The overriding method must have the same return type (or subtype).
Rule #5: The overriding method must not have more restrictive access modifier.
It is overloading of subclass' method. That means B.a(int x) is an overloaded version of B.a().
Class A has not any method with the signature with public void a(int x). So it's overloading of B's method public void a().

Hiding methods in subclass

I have a abstract superclass with some implemented methods.
Is it possible to hide methods from this superclass in an subclass inheriting from this superclass? I don't want to have some methods visible from the superclass in some of the subclasses. Last but not least, is it possible to change the number of arguments for a method in the subclass which has the same name in the superclass?
Let's say we have a method public void test(int a, int b) in the superclass but now I want a method public void test(int a) in the subclass which calls the superclass function and the method from the superclass not visible anymore.
Is it possible to hide methods from this superclass in an subclass inheriting from this superclass?
If you make the method private in the super class, it won't be visible in the subclass (or to any one else).
If you need the method in the base class to be public however, there is no way of hiding it in the subclass by for instance overriding it with a private implementation. (You can't "reduce visibility", i.e. go from for instance public or protected to private in a subclass.)
The best workaround is probably to override the method and throw for a runtime exception such as UnsupportedOperationException.
is it possible to change the number of arguments for a method in the subclass which has the same name in the superclass?
No, you can't change the signature. You can create another method with the same name and a different number of arguments but this would be a different (overloaded) method and the method in the base class would still be visible.
You can't completely hide a method from superclass, it's always possible to call, e.g.
MyBase o = new MyClass();
o.test(1, 2);
However, you can override the method in a specific way:
class MySuper {
public void test(int a, int b) {; }
}
class MyClass extends MySuper {
#Deprecated
#Override
public void test(int a, int b) {
throw new UnsupportedOperationException("Do not call this method, call test(int a) instead!");
}
public void test(int a) { ; }
}
No you cannot hide a public method in a child, for instance by making the method private there.
The reason is that having an instance of the child class, you may always cast it to the base class, and call the method there.
So this behaviour is logical. Either redesign the class hierarchy or create a new class if this is becoming a too ugly API.
You may however override the method and
/**
* Use <code>test(a)</code> instead.
* #param a.
* #param b.
*/
#Deprecated
#Override
public void test(int a, int b) {
throw new UnsupportedOperationException("Use test(int) instead.");
}
public void test(int a) { // Overloaded method
int b = ...;
super.test(a, b);
}
Overloading a method is possible: same name, different parameter types.
Java doesn't support reducing visibility.
There is a way to do something like this but it's complex:
You need to create an interface for the parent type. This interface doesn't need to have methods.
You create another, new type Delegate which implements the method public void test(int a, int b)
You delete the current parent type.
You create two new types which implement the interface. One delegates the call test(a,b) to Delegate and the other one creates a new method test(a) which eventually uses a Delegate instance.
So the type which implements the old code is never visible to the outside world (it could be a package private class).

What is "override-equivalence" and how is it related to #Override?

Reading the Javadoc for the #Override annotation, I came across the following rule:
If a method is annotated with this
annotation type compilers are required to generate an error message
unless at least one of the following conditions hold:
The method does override or implement a method declared in a supertype.
The method has a signature that is override-equivalent to that of any public method
declared in Object.
I'm clear on the first point, but I'm unsure about the second one.
What does it mean by "override-equivalent"? How are public methods of Object special in this respect? And why is this not covered under the first criterion?
Moreover, this is only true of the Java 7+ documentation. The Java 6 doc doesn't say anything about override-equivalence. Why the change?
Update:
After further consulting the JLS (Section 8.4.2), I found the following explanation of override-equivalence:
The signature of a method m1 is a subsignature of the signature of a method m2 if
either:
m2 has the same signature as m1, or
the signature of m1 is the same as the erasure (ยง4.6) of the signature of m2.
Two method signatures m1 and m2 are override-equivalent iff either m1 is a
subsignature of m2 or m2 is a subsignature of m1.
As far as I can tell, this answers the first question ("What does it mean?") and the third question ("Why doesn't the first condition cover this?").
If I understand correctly (please inform me if I don't!), there is only one case where two methods are override-equivalent and which doesn't fall under the first condition of the original question. This is the case when the erasure of the signature of the subclass method is the same as the signature of the superclass method, but not the other way around.
The second condition of the original question, then, would only come into play when we attempt to add type parameters when attempting to "override" a public method of the Object class. I tried the following simple example to test this, with an unused type parameter:
public class Foo {
#Override
public <T> boolean equals(Object obj) {
return true;
}
}
Of course, this class doesn't compile, because the method doesn't actually override the equals method and thus clashes with it. But I also still receive a compiler error for using the #Override annotation. Am I wrong in assuming that this example meets the second condition for #Override usage? Or is the compiler generating this error despite not being required to?
The reason for this is to allow you to use the #Override annotation in interfaces, which do not inherit from Object but implicitly declare all public methods from Object (see JLS section 9.2 interface members). You are thus allowed to declare an interface like:
interface Bar { #Override int hashCode(); }
However, you would not be allowed to declare the following interface:
interface Quux { #Override Object clone(); }
since the clone() method is not implicitly declared in an interface (it is not public).
This is described in JLS section 9.6.3.4 #Override (the Javadoc for #Override still refers to an old section number)
Your question is basically a design question and JLS explains its:
"The notion of subsignature is designed to express a relationship
between two methods whose signatures are not identical, but in which
one may override the other. Specifically, it allows a method whose
signature does not use generic types to override any generified
version of that method. This is important so that library designers
may freely generify methods independently of clients that define
subclasses or subinterfaces of the library."
Your code is not a valid example of this , see the below code it works:
public class SubSignatureTest extends SignatureTest {
#Override
public List test(Collection p) {
return null;
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class SignatureTest {
public <T> List<T> test(Collection<T> t) {
return null;
}
}
Whole point is that signature of superclass and subclass should be same after erasure.
EDIT:
When we talk of override equivalence then parent class should have generic method and child class should have non generic method. Here is an example to explain this .Below code will not work because child class have generic method. For a moment lets assume that java allowed that then the call in main method will always fail :
class A{
public int compareTo(Object o){
return 0;
}
}
class B extends A implements Comparable<B>{
public int compareTo(B b){
return 0;
}
public static void main(String[] argv){
System.out.println(new B().compareTo(new Object()));
}
}
In class B method will be like this after compilation:
public int compareTo(Object x){
return compareTo((B)x);
}
Which means this is always error: new B().compareTo(new Object()) .
Therefore java will not allow child class to have generic method if parent class has non generic method. So you can't define override equivalence methods for object class.
Hope that clarifies.
I used the post http://lists.seas.upenn.edu/pipermail/types-list/2006/001091.html for reference, it has lot more details.

trying to understand implicit superinterfaces

Sorry to bring back the dead. But I still don't clearly understand what this section of specification states.
If an interface has no direct superinterfaces, then the interface
implicitly declares a public abstract member method m with signature
s, return type r, and throws clause t corresponding to each public
instance method m with signature s, return type r, and throws clause t
declared in Object, unless a method with the same signature, same
return type, and a compatible throws clause is explicitly declared by
the interface. It is a compile-time error if the interface explicitly
declares such a method m in the case where m is declared to be final
in Object.
Given
interface Testing
{
void test();
}
public class Test{
public static void main(String[] args) {
Testing t = new Testing(){
#Override
public void test(){
}
};
t.test();
t.toString();
}
}
Now as the spec states that the above will change to
interface Testing
{
void test();
String toString();
//other non-final methods of Object
}
public class Test{
public static void main(String[] args) {
Testing t = new Testing(){
#Override
public void test(){
}
};
t.test();
t.toString();
}
}
Also. please confirm if there is an hierarchy of interfaces then all of them get these abstract methods.
What it means is that every class extends Object (at some point in its class heirarchy). However, interfaces do not extend Object. This is to avoid the problems that arise from multiple inheirtance.
Since interfaces do not extend Object that would mean we were unable to use methods like toString if the type (not class) of the object we had access to was an interface. But we know those methods must be available since all classes at some point extend from Object. Therefore, to get around this problem all of Object's not final methods are implicitly declared in all interfaces that have no superinterfaces. These contracts of these methods are always satisfied since all classes must at some point extend from Object.
TL;DR -- it's a trick to make sure we can access the methods made available by Object when we have an instance of some class stored in variable that's type is an interface (eg. Serializable)
edit: To answer your question, You're slightly off. All non-final methods of Object are added to an interface (whether they are used or not) if that interface has no parent interface AND for each method to added: that there is no matching method is explicitly declared by the interface.
As long as there is no super interface to an interface it gets the implicit declaration of the Object class methods. As long as these methods are included in the interface. Every interface that either extends or implements this interface doesn't see much difference between the methods that are explicitly declared by this interface or it got implicitly. That point forward that interface is as good as declared them explicitly.

Categories