Javaでは、すべてのクラスが暗黙的にObjectクラスを拡張します。つまり、これはObjectクラスのオブジェクトを作成できることを意味しますか?
public static void main(String[] args) {
Object ob=new Object();
// code here ....
}
試してみると、コンパイルして正常に実行されました。その場合、一般的にObjectクラスのオブジェクトを作成するのはいつですか。
Javaでは、すべてのクラスが暗黙的にObjectクラスを拡張します。つまり、これはObjectクラスのオブジェクトを作成できることを意味しますか?
public static void main(String[] args) {
Object ob=new Object();
// code here ....
}
試してみると、コンパイルして正常に実行されました。その場合、一般的にObjectクラスのオブジェクトを作成するのはいつですか。
You could instantiate an instance of an Object
if you want to do a synchronization lock.
public void SomeClass {
private Object lock = new Object();
private SomeState state;
public void mutateSomeSharedState() {
synchronized(lock) {
//mutate some state
}
}
public SomeState readState() {
synchronized(lock) {
//access state
}
}
}
It might be necessary to do this when this
is already used to lock some other state of the same object, or if you want to have your lock be private (ie, no one else can utilize it). Even if it isn't necessary, some people prefer to do things that way. This is merely an example of when someone might do it.
Normally we don't create an object of the Object class directly. Usually, we create instances of direct/indirect subclasses of Object.
A scenario where we create an instance of Object is to create an object to synchronize threads.
Eg:
Object lock = new Object();
//...
synchronize( lock ) {
//...
//...
}
However the Object class is used a lot to describe parameters of methods and of instance variables that may assume values of different classes (polymorphism).
Eg:
void example(Object arg) {
// ...
System.out.println( "example=" + arg.toString() );
}
Object foo = returnObject();
Sometimes the use of Generics may be better than using Object to describe parameters and variables.
For the most part I believe Object
is no longer used explicitly.
Since Java's debut of Generics, casting to the Object
class is almost non-existent.
Since java.lang.Object is the super most class, it can be substituted with any instance we create. This concept is very useful when you not aware of the type( eg: A method which conditionally returns different types , Collections with multiple types)
Also commonly used when you want to instantiate class from String,or execute a method using reflections.
However, direct usage of Object is getting redundant due to Generics. Cheers Satheesh