<<< The Class class     Index     The equals( ) method >>>

13. Access to object's type

  • Code that tests an object's type:

    
        Product p = new Book();  // create a Book object
        if ( p.getClass().getName().equals("Book") ) {
            System.out.println("This is a Book object");
        }
    
    

    The console output:

    
        This is a Book object
    
    
  • An easier way to test an object's type:

    
        Product p = new Book();  // create a Book object
        if ( p instanceof Book ) {
            System.out.println("This is a Book object");
        }
    
    
  • The console output:

    
        This is a Book object
    
    
<<< The Class class     Index     The equals( ) method >>>