淘先锋技术网

首页 1 2 3 4 5 6 7

先给出结论:

instanceof就能转

  1. 子类继承拥有父类所有属性
  2. 父类不能访问其子类中属性
  3. 子类一定能转为父类,父引用类可以强转为子类,父类、父其他引用类、其他子类不能(强)转为子类
  4. 子类转父类本质还是子类,属性值不丢失,但是不能修改子类属性值;父引用类本质是子类,但是不能设置子类属性值,强转子类后可设置子类属性值

这里的父引用类即为Base base = new Child();这种声明,详见代码。

代码说明:

/** 父类 */
@Data
@ToString(includeFieldNames = false)
public class Base {
    private Integer id;
    private String baseStr;
}

/** 子类1 */
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true, includeFieldNames = false)
public class Child extends Base {
    private String childStr;
    private String test;
}

/** 子类2 */
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true, includeFieldNames = false)
public class Other extends Base {
    private String otherStr;
    private String test;
}

/** 测试类 */
public class AppTest {
	
    @Test
    public void testExtends() {
        Base base = new Base();
        base.setId(0);
        base.setBaseStr("父");
        println("父类", base); // 父类:Base(0, 父)

        Child child = new Child();
        child.setId(1);
        child.setBaseStr("父");
        child.setChildStr("子");
        child.setTest("child");
        println("子类", child); // 子类:Child(super=Base(1, 父), 子, child)

        Base base1 = new Child();
        base1.setId(2);
        base1.setBaseStr("父");
        println("父引用类", base1); // 父引用类:Child(super=Base(2, 父), null, null)

        Base base2 = child;
        base2.setId(3);
        println("子类转父类", base2); // 子类转父类:Child(super=Base(3, 父), 子, child)

        Child child1 = (Child) base1;
        child1.setChildStr("子");
        println("父引用类强转子类", child1); // 父引用类强转子类:Child(super=Base(2, 父), 子, null)

        //Child child2 = (Child) base;
        //child2.setChildStr("子");
        //System.out.println(base instanceof Child); // false
        //println("父类强转子类", child2); // java.lang.ClassCastException: vo.Base cannot be cast to vo.Child

        Base base3 = new Other();
        base3.setId(4);
        base3.setBaseStr("父");
        println("父其他引用类", base3); // 父其他引用类:Other(super=Base(4, 父), null, null)
        
        //Child child3 = (Child) base3;
        //child3.setChildStr("子");
        //System.out.println(base3 instanceof Child); // false
        //println("父其他引用类强转子类", child3); // java.lang.ClassCastException: vo.Other cannot be cast to vo.Child
    }

	/** 父类能接受所有子类参数,且属性值不丢失 */
    private void println(String desc, Base base) {
        System.out.println(desc + ":" + base);
    }
}