JavaCodingNerd

Java Coding Nerd. This Blog will feature content-rich articles, tutorials and own opinions on variuos programming related topcis.

Java Misc

Java Overload and Override Methods

Asynchronus REST-Calls LocalDateTimeConverter

Asynchronus REST-Calls LocalDateTimeConverter

Java offers two ways to use the same method name for different executions. You can override and overload methods. This article will discuss what rules apply for either valid overriding or overloading.

Overload a method

Overloading a method is rather simple. There is only one rule you have to consider. The method signature has to change. The method signature consists of the following: Number of arguments and order of arguments.

Thus following is a valid overloaded method.


//Overloaded Method
public String getNumbersAsString(int first, int second)
{
return String.valueOf(first + second);
}

//Overloading Method
//The method signature has to change (Number of arguments, type or order of arguments
public String getNumbersAsString(int first, float second)
{
return String.valueOf(first + second);
}

Override a method

If you want to override a method there are a few more things to take care of. These are the rules

  • the return type of the method can change BUT it has to be a subclass of the original return type
  • the access modifier has to be the same or one with a wider acess
  • if the overriden throws a checked exception the overriding class has to throw the same ore a more concrete exception of the same hierarchy
  • You can also choose to throw no exception or any runtime exception

Following is an example of valid overriding


import java.io.FileNotFoundException;
import java.io.IOException;

public class OverridingAndOverloading {

//Overriden Method
protected Number getNumber(int number) throws IOException
{
return number;
}

}
class OvveridingClass extends OverridingAndOverloading
{
//Overriding Method
public Integer getNumber(int number) throws FileNotFoundException
{
return number;
}
}

Of cource you dont have to implement all these rules in every overriden method. Just make sure you dont break any.

Make sure you remember these simple rules. Thats all you have to remember if you want to take a deeper dive into this topic make sure to check the official site from Oracle:  here

 

Spread the love

Leave a Reply

Theme by Anders Norén