1

We all know that Object class is the super class in Java. Can we add methods into the Object class? And, if we make a new class with the name Object then will the functionality of that class affect the super class Object?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Why do you want new methods in the Object class ? If you can add new methods to the new object that you are creating – Gatusko Jan 09 '17 at 13:13
  • 3
    What makes this such a bad question? You can do things *similar* to modifying `Object` in some other languages, such as adding to `Object.prototype` in JavaScript (which is a Bad Idea™, but you can do it...), or adding extension methods to `object` in C#. – T.J. Crowder Jan 09 '17 at 13:14
  • I was doing up casting and calling a method of child class but making it's reference type as it's parent class. So, I was thinking that can we make it Object class type? but it gave me error that "method is not defined for object class". So, was curious to know that can we add the new method in object class ? – Kuldeep Singh Jan 09 '17 at 13:18
  • 1
    This is the kind of problem you get into if you "mess with" the definition of `Object`: http://stackoverflow.com/questions/5071803/hacking-into-java-lang-object-calling-custom-external-class-crashes-jvm – Stephen C Jan 09 '17 at 13:28

1 Answers1

7

Can we add methods into the Object class?

No. You can subclass it, but you cannot modify it (without modifying the JDK's and JRE's runtime jars; which is a Bad Idea™).

And, if we make a new class with the name Object then will the functionality of that class affect the super class Object?

No, they'll be separate classes. Of course, calling a class Object would be confusing and surprising to people reading the code.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @KuldeepSingh: I figured. In case it wasn't clear, my comment on the question was directed at the people downvoting the question (not you). – T.J. Crowder Jan 09 '17 at 13:23
  • thanks. And, do not know why people down vote ? Means if there are people who have less knowledge are not welcome in the forum? Well thank you for the support though. – Kuldeep Singh Jan 09 '17 at 13:26
  • @KuldeepSingh: That's what I meant: I didn't see why either. (One note, though: "wanna" is not an English word, or at least, if it is it's a very new and extremely informal one [English is always changing]. The correct phrase to use in a professional context like Stack Overflow is "want to.") – T.J. Crowder Jan 09 '17 at 13:27