2015-09-07 11:44:36 -06:00
|
|
|
// typeinfo/FamilyVsExactType.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// The difference between instanceof and class
|
|
|
|
package typeinfo;
|
|
|
|
|
|
|
|
class Base {}
|
|
|
|
class Derived extends Base {}
|
|
|
|
|
|
|
|
public class FamilyVsExactType {
|
|
|
|
static void test(Object x) {
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"Testing x of type " + x.getClass());
|
|
|
|
System.out.println(
|
|
|
|
"x instanceof Base " + (x instanceof Base));
|
|
|
|
System.out.println(
|
|
|
|
"x instanceof Derived " + (x instanceof Derived));
|
|
|
|
System.out.println(
|
|
|
|
"Base.isInstance(x) " + Base.class.isInstance(x));
|
|
|
|
System.out.println(
|
|
|
|
"Derived.isInstance(x) " +
|
2015-06-15 17:47:35 -07:00
|
|
|
Derived.class.isInstance(x));
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"x.getClass() == Base.class " +
|
2015-06-15 17:47:35 -07:00
|
|
|
(x.getClass() == Base.class));
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"x.getClass() == Derived.class " +
|
2015-06-15 17:47:35 -07:00
|
|
|
(x.getClass() == Derived.class));
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"x.getClass().equals(Base.class)) "+
|
2015-06-15 17:47:35 -07:00
|
|
|
(x.getClass().equals(Base.class)));
|
2015-12-02 09:20:27 -08:00
|
|
|
System.out.println(
|
|
|
|
"x.getClass().equals(Derived.class)) " +
|
2015-06-15 17:47:35 -07:00
|
|
|
(x.getClass().equals(Derived.class)));
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
test(new Base());
|
|
|
|
test(new Derived());
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Testing x of type class typeinfo.Base
|
|
|
|
x instanceof Base true
|
|
|
|
x instanceof Derived false
|
|
|
|
Base.isInstance(x) true
|
|
|
|
Derived.isInstance(x) false
|
|
|
|
x.getClass() == Base.class true
|
|
|
|
x.getClass() == Derived.class false
|
|
|
|
x.getClass().equals(Base.class)) true
|
|
|
|
x.getClass().equals(Derived.class)) false
|
|
|
|
Testing x of type class typeinfo.Derived
|
|
|
|
x instanceof Base true
|
|
|
|
x instanceof Derived true
|
|
|
|
Base.isInstance(x) true
|
|
|
|
Derived.isInstance(x) true
|
|
|
|
x.getClass() == Base.class false
|
|
|
|
x.getClass() == Derived.class true
|
|
|
|
x.getClass().equals(Base.class)) false
|
|
|
|
x.getClass().equals(Derived.class)) true
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|