Java – this keyword & method override

this

Keyword this in Java is used to reference to the current object. You can use it :

  • to call one constructor from another constructor
  • to refer to an instance variable
  • to call another method inside the class
Java this and method overriding, <span>Java – this keyword & method override</span>, KandZ
Java this and method overriding, <span>Java – this keyword & method override</span>, KandZ

Method override

Every class in Java is descendant of the Object class. That means that your class inherits the instance methods of the Object. Those methods are:

  • clone()
  • equals(Object obj)
  • finalize()
  • getClass()
  • hasCode()
  • toString()

Overriding a method allows a subclass to change the implementation for this method that is already provided by the super/parent class. To do that you need to use @Override annotation, and implement the method again with the same amount of arguments. There is an example overriding the toString() method. Normally it will return:

Java this and method overriding, <span>Java – this keyword & method override</span>, KandZ
Java this and method overriding, <span>Java – this keyword & method override</span>, KandZ

Let’s override the method now.

Java this and method overriding, <span>Java – this keyword & method override</span>, KandZ
Java this and method overriding, <span>Java – this keyword & method override</span>, KandZ

THE END!!!

88030cookie-checkJava – this keyword & method overrideJava – this keyword & method override

Related posts

2 Thoughts to “Java – this keyword & method override

  1. […] If you want to override a method then read this post. […]

  2. […] If you want to override a method then read this post. […]

Comments are closed.