例如:

class Car {
}

class Audi extends Car {
}

class Seat extends Car {
}

class Mercedes extends Car {
}
Car car = new Audi();
// car is instance of Audi, Seat or Mercedes ?

答:「使用 "instanceof" 關鍵字。」

if (car instanceof Audi) {
    // It's an Audi, now you can safely cast it
    Audi audi = (Audi) car;
    // ...do whatever needs to be done with the Audi
}

參考:
java - Check if parent class is instance of child class - Stack Overflow
 

 

那...,我如何精準地知道,手上的物件是哪一個類別的實例呢?

答:「使用 "getClass().equals( )"。」

class Car {}
class Audi extends Car {}
class Seat extends Car {}
class Mercedes extends Car {}

public class InheritTest
{
    public static void InstTest() {
        Car car = new Audi();
        if ( car instanceof Audi ) {
            System.out.println( "car instanceof Audi" );  // v
        }
        if ( car instanceof Seat ) {
            System.out.println( "car instanceof Seat" );
        }
        if ( car instanceof Car ) {
            System.out.println( "car instanceof Car" );  // v
        }
        
        System.out.println();
        
        if ( car.getClass().equals( Audi.class ) ) {
            System.out.println( "car equals Audi.class" );  // v
        }
        if ( car.getClass().equals( Seat.class ) ) {
            System.out.println( "car equals Seat.class" );
        }
        if ( car.getClass().equals( Car.class ) ) {
            System.out.println( "car equals Car.class" );
        }
    }
    
}

參考:
java - Check if a object is a instance of a class (but not a instance of its subclass) - Stack Overflow
 

 

文章標籤
創作者介紹
創作者 Robert 的頭像
Robert

Robert 的部落格

Robert 發表在 痞客邦 留言(0) 人氣()