强转类型对象的方法依然使用自己的

  cheney

    面向对象的语言中,即使类型被转换,对象还是按照自己的真实类型调用方法。

    C++ 类型定义:

    class Base{
    
    public:
    	virtual void say(void)=0;
    };
    
    class Father :public  Base{
    
    public:
    	void say(void){
    		cout << "father" << endl;
    	}
    };
    
    class Child :public Base{
    
    public:
    	void say(void){
    		cout << "child" << endl;
    	}
    };
    

    调用:

    cout << "原始类型调用 Father: ";
    Father* f = new Father();
    f->say();
    
    cout << "通过抽象的父类调用 Father: ";
    Base *b = f;
    b->say();
    
    cout << "通过抽象的基类调用 Child: ";
    b = new Child();
    b->say();
    
    cout << "父类通过子类调用 Father: ";
    Child * c = (Child *)f;
    c->say();
    
    
    cout << "通过普通父类调用 Child: ";
    f = (Father *)b;
    f->say();
    

    输出:

    原始类型调用 Father: father
    通过抽象的父类调用 Father: father
    通过抽象的基类调用 Child: child
    父类通过子类调用 Father: father
    通过普通父类调用 Child: child
    

    java 类型定义:

    package learn;
    
    
    abstract class Base {
    	
    	abstract public void say();
    	
    }
    
    package learn;
    
    
    
    public class Father extends Base{
    
    	public static void main(String args[]){
    		System.out.print("原始类型调用 Father: ");
    		Father f = new Father();
    		f.say();
    		
    		System.out.print("通过抽象的父类调用 Father: ");
    		Base b = (Base)f;
    		b.say();
    		
    		System.out.print("通过抽象的基类调用 Child: ");
    		b = (Base)new Child();
    		b.say();
    		
    		//System.out.print("父类通过子类调用 Father: ");
    		//f = (Father)b;
    		//f.say();
    		
    		System.out.print("通过普通父类调用 Child: ");
    		Child c = (Child)f;
    		c.say();
    		
    	}
    	
    	
    	@Override
    	public void say() {
    		System.out.println("father");
    	}
    }
    
    
    class Child extends Father {
    	public void say() {
    		System.out.println("child");
    	}
    }
    

    输出:

    father
    father
    child
    

    Java 中父类强转为子类,运行时会报错。