JAVA-super关键字

super一般用于在继承方面中父类的子类中使用。

第一种
super.xxx;(xxx为变量名或对象名)
这种方法意义为,获取父类中的名字为xxx的变量或方法引用。
使用这种方法可以直接访问父类中的变量或对象,进行修改赋值等操作

第二种
super.xxx();(xxx为方法名)
这种方法意义为,直接访问并调用父类中的方法。

第三种
super();
这种方法意义为,调用父类的初始化方法,其实就是调用父类中的public xxx()方法

例子;

public class Animal {
    String name;
    int age;
    double height;

    public Animal(){

    }

    public Animal(String name,int age,double height){
        this.name=name;
        this.age=age;
        this.height=height;
    }
}


public class Cat extends Animal{
    String furColor;
    double weight;

    //所有现象的根本原因就是:我必须先创建父类,并且只能创建一个父类。
    public Cat(){
        super();//调用父类空构造器,默认不写
    }
    public Cat(String furColor){
        super();//必须放在第一行
        this.furColor=furColor;
    }

    public Cat(String furColor,double weight){
//      super();
//      this.furColor=furColor;

        this(furColor);//第一行只能存在super构造器或者this构造器
        this.weight=weight;
    }

    //其实我就是在实现方法调用方法,只是这个方法特殊,是一个构造器
    public Cat(String name,int age,double height,String furColor,double weight){
//      this.name=name;
//      this.height=height;
//      this.age=age;

        super(name,age,height); //调用了父类的有参构造器之后,super()就不会默认给我分配了。
        this.furColor=furColor;
        this.weight=weight;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值