【JAVA学习路-think in java】p167:upcast与downcast的使用规则

package pkg;

class Useful{
	public void f() {System.out.println("f(x)");};
	public void g() {System.out.println("g(x)");};
}
class MoreUseful extends Useful{
	public void f() {System.out.println("f(x)");};
	public void g() {System.out.println("g(x)");};
	public void u() {System.out.println("u(x)");};
	public void v() {System.out.println("v(x)");};
	public void w() {System.out.println("w(x)");};
}


public class p167 {
	public static void main(String[] args) {
		Useful[] x= {new Useful(),new MoreUseful()};
		//DOWNcast one SubClass to BaseClass:x[1]
	
		x[0].f();
		x[1].g();
		//x[1].u();compile error
		((MoreUseful)x[1]).u();//DOWNCAST
		//((MoreUseful)x[0]).u();//exception thrown,but with SUCCESSFUL compiling
		}
}

OUTPUT:

f(x)
g(x)
u(x)
 

package pkg;

class FatherClass {
    int a;
    FatherClass() {
        a = 5;
    }
    public void superPrint() {
        System.out.println("Father, a =" + a);
    }
}

class SonClass extends FatherClass {
    int a;
    SonClass(int a) {
        this.a = a;
    }
    public void subPrint() {
        System.out.println("Son, a = " + a);
    }
}
public class test {
    public static void main(String args[]) {
        //*son-->father--->son:  ALLOWED
    	FatherClass f1 = new SonClass(10);
        f1.superPrint();
        //f1.subPrint();error,LOST sub-method
        SonClass sc = (SonClass) f1;
        sc.subPrint();   
        
        //* father-->son
        FatherClass f2=new FatherClass();
        //SonClass sc2=(SonClass) f2;//exception thrown,but with SUCCESSFUL compiling
        //sc2.subPrint();
    }
}

OUTPUT:

Father, a =5
Son, a = 10
 

总结:

1、欲调用子类方法,若是按son-->father-->son顺序Casting,则son对象可以调用son方法;

2、若直接将father--->son(downcast),这编译能通过,但运行时异常

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值