继承与覆盖

一 .成员变量的继承与隐藏
父类创建子类时,子类可以继承父类的成员变量和成员方法。子类在使用父类的同名变量时,父类中的同名变量就会被隐藏。
代码如下:

class Wc {
    String name;
    int age;
    public Wc(String name,int age) { //有参构造
        this.name = name;
        this.age = age;
    }
    public Wc( ) { //无参构造
        this.name = "name";
        this.age = 17;
    }
    public void Wg( ) { //显示父类中的成员变量
        System.out.println("WC "+"Name: "+this.name+"; age: "+this.age);
    }
}
class Nh extends Wc {
    String name;
    int ID; //声明新的成员变量
    public Nh( ){
        this.name = "Nh name";
        this.age = 20;
    }
    public Nh(String name,int age,int ID) {
        this.name = name;
        this.age = age;
        this.ID = ID;
    }
    public void Zj( ) { //子类中的成员变量
        System.out.println("Nh "+"Name: "+this.name+"; age: "+this.age+"; ID:"+this.ID);
    }
}
public class Giao {
    public static void main(String[ ] args){
        Nh tt1 =new Nh( ); //调用无参构造方法创建对象
        Nh tt2 =new Nh("NB",22,2022); //调用有参构造方法
        tt1.Wg();
        tt2.Wg(); //调用父类的成员方法
        tt1.Zj();
        tt2.Zj();//调用子类的成员方法
    }
}

注释:子类成员变量ID未被显式赋值,所以系统自动为其初始化为默认值0。

二.方法的继承与覆盖

子类中如果重新定义了从父类继承来的方法,则父类的这个方法在子类中会不存在,我们将情况简称方法覆盖。
代码如下:

class Fl  { //声明父类
    void Nb( ){//声明成员方法
        this.En();
        this.Dd(0);
    }
    void En( ) {//声明同类,同名,同参数成员方法
        System.out.println("父类:同类型,同名,同参数成员方法。");
    }
    void Dd(int a) {//声明同类型,同名但参数不同的成员方法
        System.out.println("父类:同类型,同名但参数不同的成员方法。");
    }
}
class Zl extends Fl {
    void Nl( ){
        this.Xh( );
        this.Aj( );
    }
    void Xh( ) {
        System.out.println("子类:同类型,同名,同参数成员方法。");
    }
    void Aj( ) {
        System.out.println("子类:同类型,同名但参数不同的成员方法。");
    }
}
public class Example {
    public static void main(String[ ] args) {
        Zl tt = new Zl( );
        tt.Nb();//调用父类的成员方法
        tt.Nl();//调用子类的成员方法w
    }
}

注释:要使子类的方法完全覆盖父类中的方法,方法类型,名称和参数必须完全一致,否则,任何一项不同均不能覆盖。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值