You can override a superclass’s methods in a subclass. Overriding means that you take the exact same method (same name, return type, parameter list; in other words, the same method signature) and you change the implementation in the subclass.

All classes implicitly inherit from a class called Object, which means that they also inherit Object’s methods and fields. When you write code for a class, it’s usually a good idea to override some of the methods in Object, such as the toString() and equals() method.

toString()

The toString() method is useful for displaying an object in a way that is readable for humans. By default (in the Object class), toString() is implemented such that if you print the object, it will print the name of the class and the location in memory that the object is stored, in hexadecimal.

Obviously, we don’t want that to happen, so to fix that we can override the toString() method in the class that we’re writing. For example, say I have a class called Point that has 2 fields x and y, which are the coordinates. It would be nice if I could display the Point object in String form as "(x, y)". I can do that by writing the code below (pay attention to highlighted portion):

class Point {
		public double x;
		public double y;
		
		public Point() {
				x = 0;
				y = 0;
		}

		public Point(double x, double y) {
				this.x = x;
				this.y = y;
		}

		@Override
		public String toString() {
				return String.format("(%f, %f)", x, y);
		}
}

Did you notice the @Override? This is called an override annotation, which you should put before the method signature of a method that overrides another method. It helps prevent mistakes when overriding. For example, if you put an override annotation above a method that doesn’t actually override anything, it will give you a compile error.

Did you notice String.format()? It’s a static method in the String class that allows you to do string formatting, which is where the %f comes in. Basically, %f is a placeholder for a floating point number (or double). The values of x and y replace wherever the %f is. Here’s an article about string formatting: https://www.javatpoint.com/java-string-format. If string formatting confuses you, you can always concatenate strings with variables normally.

Overloading vs. Overriding

Now that we know what overriding is, what’s the difference between overriding and overloading?

Here’s how you can keep the terms straight:

Overriding