3

Javaでは、すべてのクラスが暗黙的にObjectクラスを拡張します。つまり、これはObjectクラスのオブジェクトを作成できることを意味しますか?


public static void main(String[] args) {

Object ob=new Object();
    // code here ....
 }

試してみると、コンパイルして正常に実行されました。その場合、一般的にObjectクラスのオブジェクトを作成するのはいつですか。

4

4 に答える 4

7

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.

于 2012-09-24T02:11:43.030 に答える
2

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.

于 2012-09-24T02:13:12.550 に答える
0

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.

于 2012-09-24T02:21:39.517 に答える
0

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

于 2012-09-25T04:19:58.370 に答える