在 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.
由于 java.lang.Object 是最高级的类,它可以被我们创建的任何实例替换。当您不知道类型时,此概念非常有用(例如:有条件返回不同类型的方法,具有多种类型的集合)
当您想从 String 实例化类或使用反射执行方法时也常用。
但是,由于泛型,直接使用 Object 变得多余。干杯萨西什
在大多数情况下,我相信Object
不再明确使用。
自从 Java 首次推出泛型以来,Object
几乎不存在对类的强制转换。