Let’s say I have a method called mymethod()
and this method overrides the method of the super class method.
What does it mean to override a method?
Does that mean mymethod() ignores everything that is in the method of the superclass, or does that means mymethod() also includes everything in the superclass method?
When overriding a method, can I only override the methods of the same name, or I can override methods of any name?
thanks.
Overriding means that when you call a method on your object, your object’s method is called instead of the super class. The
@Overrideannotation is something you use to make sure that you are overriding the correct method of the superclass. If you annotate a method that does not exist in the superclass, the Java compiler will give you an error. This way you can be sure that you are overriding the correct methods. This is especially useful in cases like this:There is a logic-bug in the code above. You haven’t actually overridden the
Objectclass’sequalsmethod. If you add the@Overrideannotation:The Java compiler will now complain because there is no corresponding method in the parent class. You’ll then know that the correct solution is:
To call the parent class’s method, you can call
super.overriddenMethod()whereoverriddenMethodis the name of the method you have overridden. So if you want to do something in addition to what the parent class already does, you can do something like this: