继承的使用
一些关于继承的知识
1.继承的在面向对象中两个类之间中的一种关系,在java中通过关键字extends实现。
2.子类可以从父类继承所有非private的属性和方法作为自己的成员
3.一个父类可以拥有多个子类,那么什么是单重继承,什么是多重继承
单重继承比较简单结构为树状,而多重继承比较复杂结构为网状(要使用接口)。
4.我们这里先了解什么是继承,会区分和使用override和overload ,super和this。
override
- 方法名,参数和返回值完全相同
- 子类的方法不能缩小父类的方法访问权限
- 子类的方法不能抛出比父类更多的异常(但子类的方法可以不抛出异常)
- 存在父类和子类之间
- 被final定义的方法不能重写
overload
- 参数类型,个数,顺序至少有一个不同
- 不能重载只有返回值不同的方法
super 和 this
- 指代父类和子类对象的关键字
- this:1.在构造方法中使用放在第一行 2.在实例方法中使用可省略 3.使用this可区分参数和成员变量 4.区分成员变量和局部变量
class Test{
int y;
Test(){
y=10;
}
Test(int newy){
this();
y=y+newy;
}
int max(int n1,int n2) {//方法1
return n1>n2?n1:n2;
}
int max(int n1,int n2,int n3) {
int temp=this.max(n1, n2);
return this.max(temp, n3);//调用方法1
}
int change(int y) {
this.y=y;//区分成员变量和参数
return this.y;
}
int getY() {
return y;
}
int exchange() {
int y=5;
return this.y+y;//区分成员变量和局部变量
}
}
一个简单的例子
求矩形和盒子的周长和面积
思路:用继承的方法写一个父类和两个子类
代码如下:
一.首先创建一个父类
(周长和面积先定义为抽象方法,下面子类再分别写)
abstract class Shapes{//父类
protected double circumference;//周长
protected double area;//面积
abstract void setCircumference();
abstract void setArea();
//基类方法
public double getCircumference() {
return circumference;
}
public double getArea() {
return area;
}
}
二.再创建一个矩形的子类
肯定是要用到重写的
class Rectangle extends Shapes{//矩形子类
protected int height;
protected int width;
Rectangle(int h,int w){
height=h;
width=w;
}
@Override
public void setCircumference(){//重写计算周长
circumference=2*(height+width);
}
@Override
public void setArea() {//重写计算面积
area=height*width;
}
@Override
public String toString() {//这里重写了toString方法
return circumference+" "+area;
}
}
三.再根据矩形类创建它的一个子类方便求盒子(俩矩形)
这里的父类是矩形类,我调用了一个矩形类的构造方法(用别的东西,白嫖一时爽,一直白嫖一直爽)
class Box extends Rectangle{
private int height1,width1;
//当需要在子类调用父类的被重写方法时要使用super
Box(int h,int w){
super(h,w);//调用父类的构造方法 确定盒子的外边长和宽
}
Box(int h,int w,int innerw,int innerh){
this(h,w);
height1=innerh;
width1=innerw;
}
//setting getting....
public void setheight1(int innerh) {
height1=innerh;
}
public void setWidth1(int innerw) {
width1=innerw;
}
public int getHeight() {
return height1;
}
public int getWidth() {
return width1;
}
@Override
public void setCircumference() {
super.setCircumference();//调用父类的方法计算父类周长
circumference+=2*(height1+width1);
}
@Override
public void setArea() {
super.setArea();
area-=height1*width1;
}
@Override
public String toString() {
return circumference+" "+area;
}
}
四.主函数
public class jicheng {
public static void main(String[] args) {
//第一部分测试矩形的周长和面积
Rectangle r=new Rectangle(10,20);
r.setCircumference();
r.setArea();
System.out.println(r.toString());
//第二部分测试盒子的周长和面积
Box b=new Box(10,20,5,10);
b.setCircumference();
b.setArea();
System.out.println(b.toString());
}
}