A method overriding problem in upward transition

本文探讨了在继承过程中,相同名字的属性保持隐藏,而方法则在子类中覆盖的现象。通过示例代码展示了当向上转型发生时,原始方法被忽略,实际调用的是超类对象中子类的方法。

1) In the process of inheritance, the contants have same names in super class would not be overrided but be hidden. However the methods have same name and significantion in the super class would be replaced(overriding) in the subclass. When the upward transition happend, the orgin method is missed and the method in the super class's object would actually be the method in subclass.

Here is my test code.

package com.suncosmo.example;

/**
 * Created by SunZhiCong on 2015/8/20.
 */
public class TestMain {
    public static void main(String args[]){
        Human Tom = new Man("Tom");
        System.out.println(Tom.getSex());
    }
}
class Human{
    protected String name = "Human";
    protected String sex = "Humanity";
    Human(){
        System.out.println("Human!");
    }
    Human(String name){
        System.out.println("Human:"+name);
        this.name = name;
    }
    public String getSex(){
        return this.sex;
    }
}

class Man extends Human{
    //private String sex = "Male";
    Man(String name){
        //super(name);
        //this.name = name;
        this.sex = "Male";
        System.out.println("Man:"+name);
    }
    public String getSex(){
        System.out.println("Human");
        return this.sex;
    }
}

 

转载于:https://www.cnblogs.com/suncosmo/p/4746439.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值