close
例如:
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" ); } } }
文章標籤
全站熱搜
留言列表