Java中的继承

        在java中,继承是oop(面向对象编程)的重要支柱,它是java中的一种机制,通过该机制,一个类可以继承另一个类的功能(字段或者方法)。在java中,继承意味着基于现有的类创建新类。从另一个类继承的类可以重用该类的方法方法和字段。此外,您还可以向当前类添加新字段和方法。

为什么需要java继承?

(1)代码的可重用性:父类中的编写的代码对于所有子类都是通用的。子类可以直接是由使用父类的代码。

(2)方法重写:方法重写只能通过继承来实现。它是java中实现多态的方式之一。

(3)抽象:抽象的概念是通过继承来实现的,我们不必提供所有的细节。抽象仅仅向用户展示功能。

Java继承中使用的重要术语

(1)类是一组具有共同特征或者行为和公有属性的对象。类不是现实世界的实体。它只是创建对象的模板,蓝图或者原型。

(2)父类:其功能被继承的类称为超类(或者基类)。

(3)子类:继承其他类的类称为子类(或者派生类,扩展类或者子类)。除了父类的字段和方法外,子类还可以添加自己的方法和字段。

(4)可用性:继承支持可重用性的概念,当我们想要创建一个新类并且已经有一个类包含我们想要的一些代码时,我们可以从现有类派生新类,这样做,我们就重用了现有类的字段和方法。

Java中如何使用继承?

     在java中,extends关键字用于继承。使用extends关键字表明您是从现有类派生的。换句话说,“extends”是指新增加的功能。

例如:

class 子类 extends 父类

{

方法和字段;

JAVA中继承的示例

例如:在下面的示例中,类BIcycle是基类,类MountainBike是扩展Bicycle的派生类,类Test是运行程序的驱动程序类。

// Java program to illustrate the
// concept of inheritance
 
// base class
class Bicycle {
    // the Bicycle class has two fields
    public int gear;
    public int speed;
 
    // the Bicycle class has one constructor
    public Bicycle(int gear, int speed)
    {
        this.gear = gear;
        this.speed = speed;
    }
 
    // the Bicycle class has three methods
    public void applyBrake(int decrement)
    {
        speed -= decrement;
    }
 
    public void speedUp(int increment)
    {
        speed += increment;
    }
 
    // toString() method to print info of Bicycle
    public String toString()
    {
        return ("No of gears are " + gear + "\n"
                + "speed of bicycle is " + speed);
    }
}
 
// derived class
class MountainBike extends Bicycle {
 
    // the MountainBike subclass adds one more field
    public int seatHeight;
 
    // the MountainBike subclass has one constructor
    public MountainBike(int gear, int speed,
                        int startHeight)
    {
        // invoking base-class(Bicycle) constructor
        super(gear, speed);
        seatHeight = startHeight;
    }
 
    // the MountainBike subclass adds one more method
    public void setHeight(int newValue)
    {
        seatHeight = newValue;
    }
 
    // overriding toString() method
    // of Bicycle to print more info
    @Override public String toString()
    {
        return (super.toString() + "\nseat height is "
                + seatHeight);
    }
}
 
// driver class
public class Test {
    public static void main(String args[])
    {
 
        MountainBike mb = new MountainBike(3, 100, 25);
        System.out.println(mb.toString());
    }
}

输出:

No of gears are 3//(档位数为3)

speed of bicycle is

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

登陆成功200

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值