为什么不为所有对象声明 Object class?

Why not just declare Object class for all objects?

我刚看到关于 Java 的精彩教程视频,我发现对象 class 是幕后所有 class 的超级 class。因此,通过在处理列表本身时简单地声明 Object class 即可轻松处理 arraylist 中具有多种数据类型的问题。

我的问题是: 为什么不为所有对象声明 Object object = new SubObjectClass();

这是因为我还没有遇到过某种性能低下或内存问题吗?我发现了另一个问题,但我没有看到有人解释为什么不只是有 Object class 声明?

我明白为什么它在那里。如果这是一个基本问题,我深表歉意。

当然,您可以这样做,但是每次尝试通过变量访问成员时都必须进行类型转换。该类型转换检查需要时间来执行,因为它需要确保在对象的 class 与类型转换约束不匹配时抛出异常。

通过使用适当类型化的变量,大部分的咀嚼都被转移到编译时,允许(几乎)未经检查的运行时访问成员,只要对象不是 null

不使用它的一个原因可能是将对象与其他对象进行比较或分配时出现问题。

例如:

Object obj = new SubObjectclass();
SubObjectClass subobj = obj;// This will throw error. 
SubObjectClass subobj = (SubObjectClass)obj;//This will work.

你可以像你说的那样声明对象列表:

List<Object> list = new ArrayList<Object>();

这将是通用列表 'Objects' 可以存储任何类型的对象。

但是当我们尝试从这样的列表中检索项目时,问题就出现了 需要将检索到的对象转换为特定的对象类型。 为了进一步处理。

我们不确定哪个对象会从列表中消失。

这样做的另一个问题是您不能使用超类的对象访问子类的变量或方法。它只能访问超类的变量或方法

这是例子

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
    Object obj= new subclass();
    System.out.println(obj.i);
    System.out.println(obj.abc());

    // your code goes here
}
}

class subclass
{
int a;
public int abc(){
    return 1;
}
}

这是我在尝试编译时收到的错误:

Main.java:13: error: cannot find symbol
    System.out.println(obj.i);
                          ^
symbol:   variable i
location: variable obj of type Object
Main.java:14: error: cannot find symbol
    System.out.println(obj.abc());
                          ^
symbol:   method abc()
location: variable obj of type Object
2 errors

Java 中的类型擦除会对性能造成巨大影响,因为所有内容都必须装箱和拆箱。正如已经提到的,您也可以在 C# 中创建对象集合,但应避免使用。

What are the differences between Generics in C# and Java... and Templates in C++?

http://www.jprl.com/Blog/archive/development/2007/Aug-31.html