简体   繁体   English

在 Java 中使用 Class 和 Object 关键字

[英]Use of Class and Object Keyword in Java

Can someone provide a practical example (or two if possible) to explain when or why you would use the "Object" and "Class" keywords in Java.有人可以提供一个实际示例(或两个如果可能的话)来解释您何时或为什么要使用 Java 中的“对象”和“类”关键字。 Unfortunately after reviewing online explanations it still isn't really clear why you would declare something as "Object obj" or similarly "Class cls" for example.不幸的是,在查看了在线解释之后,仍然不清楚为什么您要将某些东西声明为“Object obj”或类似的“Class cls”。

Object and Class are not keywords; ObjectClass不是关键字; rather, they are classes.相反,它们是类。

You can use Object as a generic class eg create a generic array as shown below:您可以使用Object作为通用 class 例如创建一个通用数组,如下所示:

enum DAY {
    SUN, MON, TUE, WED, THU, FRI, SAT;
}

public class Main {
    public static void main(String[] args) {
        Object[] arr = { 1, "One", 1.5, true, DAY.THU };
        for (Object obj : arr) {
            System.out.println(obj);
        }
    }
}

Output: Output:

1
One
1.5
true
THU

The class, Class is most commonly used when dealing with reflection . class, Class在处理反射时最常用。

The important thing to know is that Object is a superclass to all objects.重要的是要知道 Object 是所有对象的超类。 If you want to use an array containing objects of different classes which do not share other more specific superclasses you may just use an Object-Array:如果你想使用一个包含不同类的对象的数组,这些对象不共享其他更具体的超类,你可以只使用一个 Object-Array:

Object[] arr = new Object[2];
arr[0] = new Double(2.3);
arr[1] = new Integer(4);

int sumOfIntegers = 0
for(int i = 0; i < arr.length; i++){
    if(arr[i] instanceof Integer){
        sumOfIntegers += (Integer)arr[i];
    }
}

Normally you should try to prevent those structures but for instance some libraries always just return objects to give the responsibility to check/know the types to you.通常您应该尝试阻止这些结构,但例如某些库总是只返回对象以负责检查/了解类型给您。

Class is just kind of a wrapper object for classes containing some metadata. Class 只是 object 的一种包装器,用于包含一些元数据的类。

Here are two examples .这里有两个例子 But of course there is a huge amount of possibilities.但是当然有很多可能性。

Many methods may request an Object and then adapt their behavior accordingly.许多方法可能会请求 Object,然后相应地调整它们的行为。 Here for example by retrieving the object Class at runtime:例如,通过在运行时检索 object Class :

public static void displayObject(Object o) {
    // Using Class of object instance:
    if(o.getClass().isAssignableFrom(GoodLookingItem.class)) {
        System.out.println((GoodLookingItem)o).toNiceString());
    }
    // Using class of object instance through instanceof
    else if(o instanceof PrettyItem) {
        System.out.println((PrettyItem)o).toPrettyString());
    }
    // No class of interest here: default to toString() method of native Object class:
    else {
        System.out.println(o.toString());
    }
}

Another example here is by using a Map of objects where typically the caller of put() and get() methods will know which kind/class of objects the map will return.此处的另一个示例是使用 Map 对象,通常 put() 和 get() 方法的调用者将知道 map 将返回的对象类型/类别。 This is quite common when you define complex datastructures, ie when building a Cache.这在您定义复杂的数据结构时很常见,即在构建缓存时。

Map<String,Object> simpleStoreMap = new HashMap<>();
// Put whatever you wish:
simpleStoreMap.put("GoodLookingItem-1", new GoodLookingItem());
simpleStoreMap.put("PrettyItem-1", new PrettyItem());
simpleStoreMap.put("SomeInteger-123", 123);

// Get whatever you want and cast it or not..:
Object obj1 = simpleStoreMap.get("GoodLookingItem-1");
PrettyItem obj2 = (PrettyItem)simpleStoreMap.get("PrettyItem-1");
Integer obj3 = (Integer)simpleStoreMap.get("SomeInteger-123");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM