继承

继承:{

事物之间是存在关系的
* 继承关系:某事物是某事物的一种
* 1.提高代码的复用性
* 2.让类与类之间产生的关系,提供了多态的前提
*
*
* 注意:
* 1.Java是可以多层继承的,但是不能继承多个
* 2.不要仅为了获取其他类的某个功能而去继承
* 类与类之间要有所属(is a)关系,xx1是xx2的一种

.0

}

子父类之间的变量特点:{

当子类People继承父类Animal时就获得了super指向了父类,在子类中没有找到age的话就会通过super去父类寻找

还可以通过super点来访问父类中的变量和方法

}

子父类中的函数覆盖:{

*函数的覆盖(重写)(和重载不一样,重载是参数个数或者参数类型不一样)
* 覆盖的应用场景:
* 当子类需要父类的功能,而功能主体子类需要有自己特有内容时,
* 可以重写父类中的方法,这样,即沿袭了父类的功能,有定义了子类的特有内容。
*
* 重写的注意事项:
* 1.父类中私有的函数不能重写
* 2.子类重写父类函数时,权限不能小于父类
* public>protected>default>private
* 3.静态只能覆盖静态函数

当子类的访问权限小时将不能重写父类函数

想要重写父类函数必须要大于父类的访问权限或者同级

}

子父类构造函数:{

为了避免代码的重复性所以将所需的重复代码放入父类中的构造函数中

访问父类的构造函数,需要使用super关键字调用

super关键字中包含父类中构造函数的参数,如果是无参构造函数的话,super();即可

注:super关键字的调用要放在方法开头的第一句

 class Animal {//父类
    int age;
    String color;
    public Animal(int age,String color){
        this.age=age;
        this.color=color;
        System.out.println("有参构造函数----父类");
    }
    public Animal(){
        System.out.println("无参构造函数----父类");
    }
}
//子类
class Cat extends Animal {
    String name;
    public Cat(String name,int age,String color){
        //调用父类中的构造函数
        super(age,color);
        this.name=name;
        System.out.println("有参构造函数----子类");
    }

}
//子类
class Dog extends Animal {
    String name;
    public Dog(String name,int age,String color){
        //调用父类中的构造函数
        super(age,color);
        this.name=name;

    }
}
public class Note {
    public static void main(String[] args) {
    Cat cat=new Cat("小花",2,"黄色");
    System.out.println(cat.name+"----"+cat.age"----"+cat.color);
    }
}

该代码中父类的构造函数先调用

class Animal {//父类
    int age;
    String color;
    public Animal(int age,String color){
        this.age=age;
        this.color=color;
        System.out.println("有参构造函数----父类");
    }
    public Animal(){
        System.out.println("无参构造函数----父类");
    }
}
//子类
class Cat extends Animal {
    String name;
    public Cat(String name,int age,String color){
        //调用父类中的构造函数
//        如果写了调用父类构造函数的代码那么就会将隐式(super())代码覆盖掉
        super(age,color);
        this.name=name;
        System.out.println("有参构造函数----子类");
    }

}
//子类
class Dog extends Animal {
    String name;
    public Dog(String name,int age,String color){
//        调用父类中的构造函数
//        super();隐式存在的代码
        this.name=name;
        System.out.println("有参构造函数----子类");

    }
}
class Pig extends Animal{
    //子类中没写构造函数,就相当于存在以下这样的代码
   /* public Pig(){
        super();
    }*/
}
public class Note {
    public static void main(String[] args) {
//    Cat cat=new Cat("小花",2,"黄色");
//    System.out.println(cat.name+"----"+cat.age+"----"+cat.color);
        new Dog("小黄",1,"白色");
    }
}

 

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值