noquery
noquery

Reputation: 1945

How to override toString() of final class in java

While profiling my java program through YourKit, yourkit reported me where the problem is;

enter image description here

Although my program is small and I can find out the place where problem is but I want to override toString() of Integer. So that yourkit can print it.

how can I do this?

*I have some ways to do it. Like if I on allocation monitor of yourkit profiler, or i just call toString() when i initialize an object. So I can match it with yourkit report. But I am looking for some good solution.

Upvotes: 0

Views: 3269

Answers (3)

Rangi Lin
Rangi Lin

Reputation: 9461

From Java Specification

Chapter.8 Classes - final classes

final Classes

  • Because a final class never has any subclasses, the methods of a final class are never overridden

And Integer is a final class

public final class Integer extends Number implements Comparable<Integer>

So you are not allow to override anything inside Integer.

However, Integer has already overridden toString() method which will display the number.

public String toString() {
    return String.valueOf(value);
}

So I believe there is probably something to do with how Yourkit display Java objects

Upvotes: 2

user851031
user851031

Reputation:

The Integer class is final. Therefore, you cannot overload it as you can only overload a method through making a class which inherits from the parent.

see http://www.roseindia.net/javatutorials/final_methods.shtml

Upvotes: 0

Gili
Gili

Reputation: 90150

YourKit might allow you to customize its output, but there is no way for you to override public final methods in Java proper, especially for core API classes such as java.lang.Integer.

Upvotes: 1

Related Questions