1. 语法:
class 类名 extends 父类名
java中继承只能单继承。
B类继承A类,
A类称作父类,基类,超类,superclass
B类称作子类,派生类,subclass
子类继承父类会将父类中所有的数据全部继承,包括私有的也会继承,构造方法除外。
继承最基本的作用是:代码重用。最重要的作用是:方法覆盖和多态。
2. 继承中的构造方法
子类在构造的过程中必须先调用父类的构造方法。
如果子类的构造函数中,没有显示的去调用父类的构造方法,系统默认调用父类的缺省构造器。
如果子类的构造函数中,没有显示的去调用父类的构造方法,父类又没有缺省构造器,编译报错。
3. super 关键字
指向父类对象
应用场景:
1. 子类构造函数,显示地去调用父类构造函数。
2. 父类中有这个数据,结果子类中也有这个数据,非要在子类中访问父类中的那个数据,必须使用“super.”。
注意:虽然super(实参);执行了,但是并不会创建父类对象。
4. 方法重写(@Override)
当父类中的方法无法满足子类需求的时候,需要方法重写
注意:
第一:发生在具有继承关系的父子类之间。
第二:返回值类型一致,方法名一致,参数列表一致。
第三:修饰符权限不能更低。
第四:抛出的异常不能更多。
第五:构造方法不能被继承,所以不存在覆盖。
第六:私有的方法无法被覆盖。
第七:静态的方法不存在覆盖。
第八:覆盖只是针对成员方法,和成员变量无关。
5、举个例子
class Flower {
private String color;
private float price;
Flower(String color, float price) {
this.color = color;
this.price = price;
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setPrice(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
public String showInfo(){
String info = "花的颜色是:"+this.color+",花的价格是:"+this.price;
return info;
}
}
class Rose extends Flower{
private String originPlace;
Rose(String color, float price,String originPlace){
super(color,price); //调用父类的构造方法
this .originPlace= originPlace;
System.out.println("我是rose的构造函数");
}
public void setOriginPlace(String originPlace) {
this.originPlace = originPlace;
}
public String getOriginPlace() {
return originPlace;
}
@Override
public String showInfo(){ //重写父类的方法
String info = "花的颜色是:"+super.getColor()+",花的价格是:"+super.getPrice()+",产地是:"+originPlace;
return info;
}
}
public class Demo{
public static void main(String[] args) {
Rose rose = new Rose("红色",30.0F,"海南");
System.out.println(rose.getColor()); //子类继承父类的方法,可以直接调用
System.out.println(rose.getPrice()); //子类继承父类的方法,可以直接调用
System.out.println(rose.getOriginPlace());//子类调用自己的方法
System.out.println(rose.showInfo());//如果方法被重写,子类默认调用的是自己重写后的方法
}
6、超类的重写
因为我们所有的类都继承自超类,所以超类的方法我们也是可以重写的,比如说 equals
我现在有个需求,我有两只猫,我神经比较大条,只要这两只猫名子一样,颜色一样,我就认为是一只猫,如果直接用equals,因为不是一个对像,所以无法相等,要想让equals按我的想法实现,必须对equals进行重写
class Cat {
private String name;
private String color;
Cat(String name, String color) {
this.name = name;
this.color = color;
}
public boolean equals(Cat cat) { //重写equals方法
if ((this.color.equals(cat.color)) && (this.name.equals(cat.name))) {
return true;
} else {
return false;
}
}
}
public class Demo {
public static void main(String[] args) {
Cat cat1 = new Cat("小白", "白色");
Cat cat2 = new Cat("小白", "白色");
Cat cat3 = new Cat("小花", "花色");
System.out.println(cat1.equals(cat2));
System.out.println(cat1.equals(cat3));
}
}
运行结果:
true
false