super关键字:
super关键字的使用:
-
super理解为:父亲的
-
super可以用来调用属性、方法、构造器
-
super的使用:调用属性和方法
3.1 我们可以在子类的方法或构造器中,通过使用“super.属性”或“super.方法”的方式
显示的调用父类中声明的属性或方法。但是通常情况下,我们习惯省略“super”
3.2 特殊情况:当子类和父类中定义了同名的属性时,我们要想在子类中调用父类中
声明的属性,则必须显示的写成“super.属性”来明确指明调用的是父类的属性
3.3 特殊情况:当子类重写了父类中的方法后,我们如果还想调用父类中被重写的方法
则必须在方法前面显示的加上“super.”,用这种方法来指明我们调用就是父类中被重写的方法
-
this. :当前对象或子类的,当你使用this的时候,控制台会先在当前类或子类中找如果没有再去父类中找
-
super.:父类的,当你使用super的时候,控制台就直接去父类中找了,不会在子类找
-
super的使用:调用构造器
6.1 我们可以在子类的构造器中显示的使用“super(形参列表)”的方式,调用父类中声明的指定的构造器
6.2“super(形参列表)”的使用,必须声明在子类构造器的首行
6.3我们在类的构造器中,针对于this(形参列表)和super(形参列表),只能二选一,不能同时出现
6.4在构造器的首行,没有显示的声明this(形参列表)或super(形参列表)时,则默认调用的是父类中空参的构造器,如果父类中没有空参的构造器,则会报异常
6.5在类的多个构造器中,至少有一个构造器使用“super(形参列表)”的构造器,来调用父类的结构,如果没有显示的父类,则默认调用Object类。
我们来看我们使用super关键字的代码:(主要看第二个类Cylinder类)
package com.myobjectoriented2.nonworking;
/**
*
* @Desciption
* @author Abraham
* @email 1290807550@qq.com
* @version JDK1.8
* @date 2021年3月27日上午10:40:44
*/
public class Circle {//圆
private double radius;
public Circle() {
this.radius = 1;
}
public void setRadius(double radius) {
this.radius =radius;
}
public double getRadius() {
return this.radius;
}
public double findArea() {
return Math.PI*radius*radius;
}
}
package com.myobjectoriented2.nonworking;
public class Cylinder extends Circle {//圆柱
private double length;
public Cylinder() {
this.length = 1;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double findVolume() {
//return Math.PI*getRadius()*getRadius()*length;使用了super关键字
return super.findArea()*length;
}
public double findArea() {
return (Math.PI*getRadius()*getRadius()*2)+(Math.PI*getRadius()*2*getLength());
//下面的是使用了super关键字的
//return super.findArea()*2+(Math.PI*getRadius()*2*getLength());
}
}
package com.myobjectoriented2.nonworking;
public class Cylindertest {//测试类
public static void main(String[] args) {
Cylinder cylin=new Cylinder();
// //没有重写以前的计算结果,这个时候cylin计算面积调的是父类Circle里面的
// cylin.setRadius(1);
// System.out.println(cylin.findArea());//计算底面积3.141592653589793
// cylin.setLength(3);
// System.out.println(cylin.findVolume());//计算圆柱体积 37.69911184307752
//接下来我们看看重写以后怎么样的:
cylin.setRadius(2);
System.out.println(cylin.findArea());//计算圆柱的表面积37.69911184307752
cylin.setLength(2);
System.out.println(cylin.findVolume());//计算圆柱的体积25.132741228718345
}
}