BOOKJAVA Telegram 3942
🧠 Можно ли переопределить getClass() в Java?

Нет, нельзя.
Метод getClass() в java.lang.Object объявлен так:


public final native Class<?> getClass();


📌 Почему:

- final — запрещает переопределение в наследниках.
- native — реализован в JVM, а не на Java.
- Гарантирует, что при вызове obj.getClass() всегда вернётся реальный класс объекта, без подмен и сюрпризов.

💡 Если хотите вернуть “свой” тип, делайте отдельный метод:


class MyClass {
public String getTypeName() {
return "CustomType";
}
}


⚠️ Переопределяемый getClass() сломал бы рефлексию, сериализацию и кучу системных механизмов. Именно поэтому Java защищает его.

👉 @BookJava
👍52



tgoop.com/BookJava/3942
Create:
Last Update:

🧠 Можно ли переопределить getClass() в Java?

Нет, нельзя.
Метод getClass() в java.lang.Object объявлен так:


public final native Class<?> getClass();


📌 Почему:

- final — запрещает переопределение в наследниках.
- native — реализован в JVM, а не на Java.
- Гарантирует, что при вызове obj.getClass() всегда вернётся реальный класс объекта, без подмен и сюрпризов.

💡 Если хотите вернуть “свой” тип, делайте отдельный метод:


class MyClass {
public String getTypeName() {
return "CustomType";
}
}


⚠️ Переопределяемый getClass() сломал бы рефлексию, сериализацию и кучу системных механизмов. Именно поэтому Java защищает его.

👉 @BookJava

BY Библиотека Java разработчика




Share with your friend now:
tgoop.com/BookJava/3942

View MORE
Open in Telegram


Telegram News

Date: |

In 2018, Telegram’s audience reached 200 million people, with 500,000 new users joining the messenger every day. It was launched for iOS on 14 August 2013 and Android on 20 October 2013. Although some crypto traders have moved toward screaming as a coping mechanism, several mental health experts call this therapy a pseudoscience. The crypto community finds its way to engage in one or the other way and share its feelings with other fellow members. End-to-end encryption is an important feature in messaging, as it's the first step in protecting users from surveillance. Just at this time, Bitcoin and the broader crypto market have dropped to new 2022 lows. The Bitcoin price has tanked 10 percent dropping to $20,000. On the other hand, the altcoin space is witnessing even more brutal correction. Bitcoin has dropped nearly 60 percent year-to-date and more than 70 percent since its all-time high in November 2021. How to build a private or public channel on Telegram?
from us


Telegram Библиотека Java разработчика
FROM American