We know java.lang
is the default package in java, and we don't need to import anything from them.
java.lang
? java.lang
? java.lang
with any other package (I mean, If I re-write all the classes and interfaces from java.lang
to java.lang1
, then can I set java.lang1
as default) ? I'm sure enough that all of these are not possible to just post, "no, these are not possible." Note you can't do it with reflection since these are all compile-time questions.
(4), "can I change the default base class from Object," is not like the others, and is the most ludicrous. That would break many many programs at compile, because even doing something like System.out.println(user)
relies on the fact that the object user
has a toString
method. In particular String
is broken, because its toString
method is inherited from Object
.
Everything else you asked is compile-time only, so less ludicrous, but still not possible.
For completeness, it also would be strange and bad practice. I've heard of a C programmer who included #define retrun return
in a headers file. So when any other developer maintaining his code saw retrun eta;
they had to dig out the headers file to know what it meant. This is write-optimized code but software engineering is about read-optimizing code (yes I'm generalizing; trying to cover this in a paragraph). Cluttered imports do that - it makes it very obscure to tell where things come from, which is fine for String
and Exception
, but problematic even for things in java.util
. Yes, this line was arbitrary at some point, but I feel it's intelligent and certainly should not include more things.
You cannot change your default package in java which is java.lang
. All classes other than this package have to be imported using import
statement. So for your 1,2 and 3
answer is no.
Can I change the base class (java.lang.Object) to some other class ?
Answer is no again (atleast not in a simple way , without messing up with bootclasspath and stuff), and why would you want to do that. You can instead say YourClass extends Object
and implement extra functionality and override existing ones, if needed. But even then all the classes would not implicitly extend from your class like they do from Object
. The recommended way to use Object
class is to override its method to implement your own functionality specific to your class (Like overriding toString()
) .
Yes you can. But it is very very uncommon.
Theoretically you could do that easily, at run-time. Use the Java Agent API to replace (wrap) the byte-code of the default Object class. And do the same for all class-loaders, where you need your custom functionality.
Note:
It's really not complicated. it's just another API.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.