关于JAVA中成员变量覆盖认识和总结

在Java的多态特点中,子类继承父类的成员变量(member variable)时,如果字面值(variable literal)不一致时。不是说子类没有继承父类的特性,而是子类将父类的特性覆盖(override)了。这时将会使用子类的成员变量,而父类的成员变量将被保护起来。如果想要使用父类的成员变量,则可以改变其布雷变量的修饰符。
下面将举一个小例子:

//定义一个父类Fruit
public class Fruit {
    String color="yellow";
    String size="small";
    //定义两个Default方法
    String getFruitColor(){
        return color;
    }
    String getFruitSize(){
        return size;
    }
}

//定义一个子类Apple
public class Apple extends Fruit {
    String apple_color="green";
    String apple_size="big";
    String getFruitColor(){
        return apple_color;
    }
    String getFruitSize(){
        return apple_size;
    }
    public static void main(String[] args) {
        Fruit f=new Apple();//创建一个Fruit类的Apple对象
        System.out.println(f.getFruitColor());
        System.out.println(f.getFruitSize());
    }
}


此时输出的结果为:
green
big

Process finished with exit code 0


以上的例子中,我们创建的Fruit类的Apple对象完全的覆盖了其父类的变量和方法。那我们如何不让子类覆盖呢,其实只需要在不想被覆盖的变量和方法前加上关键字static就可以了,因为加上static关键字下的变量和方法属于类,不随着对象而创建副本。例如:

public class Fruit {
    static String color="yellow";
    String size="small";
    //定义一个静态方法
    static String getFruitColor(){
        return color;
    }
    //定义一个Default方法
    String getFruitSize(){
        return size;
    }
}

//定义一个子类Apple
public class Apple extends Fruit {
    static String apple_color="green";
    String apple_size="big";
    //定义一个静态方法
    static String getFruitColor(){
        return apple_color;
    }
    //定义一个Default方法
    String getFruitSize(){
        return apple_size;
    }
    public static void main(String[] args) {
        Fruit f=new Apple();//创建一个Fruit类的Apple对象
        System.out.println(f.getFruitColor());
        System.out.println(f.getFruitSize());
    }
}


此时输出的结果为:
yellow
big

Process finished with exit code 0
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值