简体   繁体   中英

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. 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 and Class are not keywords; rather, they are classes.

You can use Object as a generic class eg create a generic array as shown below:

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:

1
One
1.5
true
THU

The class, Class is most commonly used when dealing with reflection .

The important thing to know is that Object is a superclass to all objects. 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[] 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.

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. Here for example by retrieving the object Class at runtime:

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. 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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