A2oz

How to Override an Inbuilt Method in Java?

Published in Java Programming 2 mins read

You cannot directly override an inbuilt method in Java. Inbuilt methods are part of the Java standard library, which is a core component of the language. These methods are final, meaning they cannot be modified or overridden.

However, you can achieve similar functionality by:

  • Extending a class: You can extend the class that contains the inbuilt method and create a new method with the same name and signature. This new method will then be used in place of the inbuilt method when you use the extended class.
  • Using composition: You can create a new class that encapsulates the inbuilt method and provides a different implementation. This approach allows you to use the inbuilt method while providing your own customization.

Here are some examples:

  • Extending the String class:

     class MyString extends String {
         @Override
         public String toUpperCase() {
             return "My String is in uppercase!";
         }
     }

    This code defines a new class MyString that extends the String class. It overrides the toUpperCase() method to return a custom string.

  • Using composition with the Integer class:

     class MyInteger {
         private Integer value;
         public MyInteger(int value) {
             this.value = value;
         }
         public int getDoubledValue() {
             return value.intValue() * 2;
         }
     }

    This code defines a new class MyInteger that uses an Integer object internally. It provides a new method getDoubledValue() that doubles the value of the Integer object.

Remember that overriding inbuilt methods is not recommended as it can lead to unexpected behavior and break existing code. It's best to use these techniques for specific purposes and with caution.

Related Articles